package com.crm.system.service.impl.contractManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.beust.jcommander.internal.Lists;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.ContractTypeEnum;
import com.crm.common.model.Enum.PaymentMethodEnum;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.model.Enum.csd.WorkLogEnum;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.ESUtil;
import com.crm.model.entity.activityManager.CustomerProductGiftActivity;
import com.crm.model.entity.cluePoolManager.ClueFollow;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.contractManager.CustomerContractDeveloper;
import com.crm.model.entity.contractReviewManager.ContractReview;
import com.crm.model.entity.couponManager.Coupon;
import com.crm.model.entity.couponManager.CouponIssued;
import com.crm.model.entity.couponManager.CustomerContractCoupon;
import com.crm.model.entity.csd.customerManager.CustomerServiceWorkLog;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.finishOrderProduct.FinishOrderProduct;
import com.crm.model.entity.messageprompt.MessagePrompt;
import com.crm.model.entity.opportunityManager.Opportunity;
import com.crm.model.entity.opportunityManager.OpportunityCollaborator;
import com.crm.model.entity.orderManager.CustomerOrderActivityRelation;
import com.crm.model.entity.orderManager.CustomerOrderGiftRelation;
import com.crm.model.entity.orderManager.CustomerProductOrder;
import com.crm.model.entity.orderManager.CustomerProductOrderDetail;
import com.crm.model.entity.productManager.CustomerMemberProduct;
import com.crm.model.entity.productManager.CustomerProduct;
import com.crm.model.entity.sys.FileUpload;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.UserInfo;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.qo.contractManager.*;
import com.crm.model.qo.contractReviewManager.ContractReviewDetailQO;
import com.crm.model.qo.couponManager.ContractCouponQO;
import com.crm.model.vo.activityManager.CustomerProductGiftActivityContractVO;
import com.crm.model.vo.customerContractManager.*;
import com.crm.model.vo.datasearch.DataSearchResultVO;
import com.crm.model.vo.opportunityManager.OpportunityContractDetailVO;
import com.crm.model.vo.orderManager.CustomerActivityOrderDetailEditVO;
import com.crm.model.vo.orderManager.CustomerProductOrderDetailEditVO;
import com.crm.model.vo.orderManager.CustomerProductOrderEditVO;
import com.crm.model.vo.returnMoney.CustFinanceProductOderVO;
import com.crm.service.activityManager.CustomerProductGiftActivityDbService;
import com.crm.service.contractManager.CustomerContractDbService;
import com.crm.service.contractManager.CustomerContractDeveloperDbService;
import com.crm.service.contractReviewManager.ContractReviewDbService;
import com.crm.service.couponManager.ContractCouponDbService;
import com.crm.service.couponManager.CouponIssuedDbService;
import com.crm.service.csd.customerManager.CustomerServiceWorkLogDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.messageprompt.MessagePromptDbService;
import com.crm.service.opportunityManager.OpportunityDbService;
import com.crm.service.orderManager.CustomerOrderActivityRelationDbService;
import com.crm.service.orderManager.CustomerOrderGiftRelationDbService;
import com.crm.service.orderManager.CustomerProductOrderDbService;
import com.crm.service.orderManager.CustomerProductOrderDetailDbService;
import com.crm.service.productManager.CustomerMemberProductDbService;
import com.crm.service.productManager.CustomerProductDbService;
import com.crm.service.returnMoney.FinishOrderDBservice;
import com.crm.service.sys.UserInfoDbService;
import com.crm.system.service.FileUploadService;
import com.crm.system.service.cluePoolManager.ClueFollowService;
import com.crm.system.service.contractManager.CustomerContractService;
import com.crm.system.service.opportunityManager.OpportunityCollaboratorService;
import com.crm.system.service.permissionManagement.SysCompanyService;
import com.crm.system.service.user.UserAccountService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.util.*;

/**
 * @author yincuimei
 * @Date 2021/3/12 10:00
 */
@Slf4j
@Service
public class CustomerContractServiceImpl implements CustomerContractService {
    @Autowired
    private CustomerContractDbService customerContractDbService;
    @Autowired
    private CustomerContractDeveloperDbService customerContractDeveloperDbService;
    @Autowired
    private CustomerDbService customerDbService;
    @Autowired
    private CustomerProductDbService customerProductDbService;
    @Autowired
    private CustomerProductOrderDbService customerProductOrderDbService;
    @Autowired
    private CustomerProductOrderDetailDbService customerProductOrderDetailDbService;
    @Autowired
    private CustomerOrderGiftRelationDbService customerOrderGiftRelationDbService;
    @Autowired
    private FileUploadService fileUploadService;
    @Autowired
    private CustomerProductGiftActivityDbService productGiftActivityDbService;
    @Autowired
    private UserInfoDbService userInfoDbService;
    @Autowired
    private UserAccountService userAccountService;
    @Autowired
    private CustomerOrderActivityRelationDbService orderActivityRelationDbService;
    @Autowired
    private CustomerOrderGiftRelationDbService orderGiftRelationDbService;
    @Autowired
    private FinishOrderDBservice finishOrderDBservice;
    @Autowired
    private ClueFollowService clueFollowService;
    @Autowired
    private OpportunityCollaboratorService opportunityCollaboratorService;
    @Autowired
    private OpportunityDbService opportunityDbService;
    @Autowired
    private CustomerProductOrderDbService productOrderDbService;
    @Autowired
    private ContractCouponDbService contractCouponDbService;
    @Autowired
    private SysCompanyService companyService;
    @Autowired
    private CustomerServiceWorkLogDbService serviceWorkLogDbService;
    @Autowired
    private CustomerMemberProductDbService customerMemberProductDbService;
    @Autowired
    private ContractReviewDbService contractReviewDbService;
    @Autowired
    private MessagePromptDbService messagePromptDbService;
    @Autowired
    private CouponIssuedDbService couponIssuedDbService;

    @Value("${esurl}")
    public String ESurl;

    /**
     * (超级管理员、普通管理员、普通用户)合同管理--合同列表
     * @param customerContractQO ---合同列表查询参数
     * @param pageIndex/pageSize ---页码、分页大小
     * @param sortName/sortOrder ---合同列表排序字段及规则
     * @param permissionType     ---权限类型(0:超级管理员;1:普通管理员;2:普通用户)
     * @author yincuimei
     */
    @Override
    public DhPageInfo<CustomerContractVO> selectCustomerContractVOList(CustomerContractQO customerContractQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String permissionType) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //增加删除状态查询条件(0:正常;1:已删除)deleteStatus
        customerContractQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

        Integer dateUnit = 0;

        if (!StringUtils.isBlank(customerContractQO.getDateType())) {
            if ("thisWeek".equals(customerContractQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(customerContractQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(customerContractQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
        }

        //获取登录人信息
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        //排序
        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("t.create_tm ").append(sortOrder);//创建时间
                }
                break;
                case "updateTm": {
                    order.append("t.update_tm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }

        List<CustomerContractVO> customerContractVOList = null;
        if (!StringUtils.isBlank(permissionType)) {
            if ("0".equals(permissionType)) {//超级管理员/客服看全部合同数据
                customerContractVOList = customerContractDbService.selectCustomerContractVOList(customerContractQO, dateUnit, order.toString(), null, null);
            } else if ("1".equals(permissionType)) {//普通管理员
                customerContractVOList = customerContractDbService.selectCustomerContractVOList(customerContractQO, dateUnit, order.toString(), null, userAccount.getCompanyId());
            } else if ("2".equals(permissionType)) {//普通用户
                customerContractVOList = customerContractDbService.selectCustomerContractVOList(customerContractQO, dateUnit, order.toString(), userAccount.getAccountId(), null);
            }
        }
        PageInfo<CustomerContractVO> pageInfo = new PageInfo<CustomerContractVO>(customerContractVOList);
        return new DhPageInfo<CustomerContractVO>(pageInfo, customerContractVOList);
    }

    /**
     * (用户系统)合同管理--合同列表
     * @param customerContractQO ---查询条件
     * @param pageIndex/pageSize ---页码/分页大小
     * @param sortName/sortOrder ---合同列表排序字段及规则
     * @return
     */
    @Override
    public DhPageInfo<CustomerContractVO> selectUserCustomerContractVOList(CustomerContractQO customerContractQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //增加删除状态查询条件(0:正常;1:已删除)deleteStatus
        customerContractQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

        Integer dateUnit = 0;

        if (!StringUtils.isBlank(customerContractQO.getDateType())) {
            if ("thisWeek".equals(customerContractQO.getDateType())) {
                //本周
                dateUnit = 1;
            }
            if ("thisMonth".equals(customerContractQO.getDateType())) {
                //本月
                dateUnit = 2;
            }
            if ("thisYear".equals(customerContractQO.getDateType())) {
                //本年
                dateUnit = 3;
            }
            if ("lastMonth".equals(customerContractQO.getDateType())) {
                //上月
                dateUnit = 4;
            }
        }

        //获取登录人信息
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();

        //排序
        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("create_tm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }

        List<CustomerContractVO> customerContractVOList = customerContractDbService.selectUserCustomerContractVOList(customerContractQO, dateUnit, order.toString(), userAccount.getAccountId());

        PageInfo<CustomerContractVO> pageInfo = new PageInfo<CustomerContractVO>(customerContractVOList);
        return new DhPageInfo<CustomerContractVO>(pageInfo, customerContractVOList);
    }

    /**
     * 合同列表--查看(根据合同ID查询合同详情)
     * @param contractId ---合同ID
     * @author yincuimei
     */
    @Override
    public CustomerContractDetailVO selectCustomerContractVODetail(String contractId) {
        CustomerContractDetailVO customerContractDetailVO = null;
        if (!StringUtils.isBlank(contractId)) {
            //1:查询合同基本信息
            customerContractDetailVO = customerContractDbService.selectCustomerContractVODetail(contractId);

            //查询合同附件URL
            if(!StringUtils.isBlank(customerContractDetailVO.getContractAnnexId())){
                FileUpload fileUploadAnnexId = fileUploadService.selectFileUploadById(customerContractDetailVO.getContractAnnexId());
                if (fileUploadAnnexId != null) {
                    customerContractDetailVO.setContractAnnexAccessUrl(fileUploadAnnexId.getAccessUrl());
                }
            }
            //查询合同审核附件URL
            if(!StringUtils.isBlank(customerContractDetailVO.getReviewAnnexId())){
                FileUpload fileUploadReviewAnnexId = fileUploadService.selectFileUploadById(customerContractDetailVO.getReviewAnnexId());
                if (fileUploadReviewAnnexId != null) {
                    customerContractDetailVO.setReviewAnnexAccessUrl(fileUploadReviewAnnexId.getAccessUrl());
                }
            }

            //2:查询合同合作开发人员信息
/*            List<String> coDeveloperIdList = null;
            List<CustomerContractDeveloper> contractDeveloperList = customerContractDeveloperDbService.selectCustomerContractDeveloperList(contractId);
            if (contractDeveloperList != null && contractDeveloperList.size() > 0) {
                coDeveloperIdList = contractDeveloperList.stream().map(CustomerContractDeveloper::getCoDeveloper).collect(Collectors.toList());
                List<String> userAccountIdList = userAccountDbService.selectUserIdListByAccountIds(coDeveloperIdList);
                customerContractDetailVO.setCoDeveloperList(userAccountIdList);
            }*/
        }
        return customerContractDetailVO;
    }

    /**
     * 合同列表--作废(根据合同ID作废合同-未生效的合同可以作废)
     * @param contractId     ---合同ID
     * @param contractStatus ---合同作废状态
     * @author yincuimei
     * 1:将合同状态置为已作废;2:将订单状态置为作废
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public JSONObject cancelCustomerContract(String contractId, String contractStatus) {
        JSONObject jsonObject = new JSONObject();
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        //先查询合同状态和回款状态(合同状态为未生效、回款状态为未回款的合同可作废)
        Map map = customerContractDbService.selectContractAndPaymentStatus(contractId);
        if(map != null){
            if("1".equals(map.get("contractStatus")) && "0".equals(map.get("paymentStatus"))){
                jsonObject.put("operateFlag","enableCancel");
            }else{
                jsonObject.put("operateFlag","disableCancel");
                return jsonObject;
            }
        }
        if (!StringUtils.isBlank(contractId)) {
            //1:将合同状态置为已作废(chs_customer_contract)
            customerContractDbService.updateContractStatusById(contractId, contractStatus);
            //2:将订单状态置为作废(chs_customer_product_order)
            customerProductOrderDbService.updateOrderStatusByContractId(contractId);
            //3：将合同绑定的商机表的合同商机置改成未创建
            CustomerContract customerContract = customerContractDbService.selectContractById(contractId);
            if(!StringUtils.isBlank(customerContract.getOpportunityId())){
                Opportunity opportunity = new Opportunity();
                opportunity.setOpportunityId(customerContract.getOpportunityId());
                opportunity.setOpportunityContractType("0");
                opportunity.setUpdateTm(new Date());
                opportunity.setUpdatePeopleId(userAccount.getAccountId());
                opportunityDbService.updateOpportunityId(opportunity);
            }
            //4、如果是余额支付，将客户的钱原路返还
            String paymentMethod = customerContract.getPaymentMethod();
            BigDecimal contractReceivables = customerContract.getContractReceivables();
            if(!StringUtils.isBlank(paymentMethod)&&!PaymentMethodEnum.OFFLINE_PAYMENT.getPaymentMethod().equals(paymentMethod)){
                //查询客户信息
                Customer customerOld = customerDbService.selectCustomerById(customerContract.getCustomerId());
                Customer customerNew = new Customer();
                customerNew.setCustomerId(customerContract.getCustomerId());
                //钱原路返回
                //2:线下支付;3:余额支付;4:转入额支付;5:余额＋转入额支付;
                switch (paymentMethod) {
                    case "3": {
                        customerNew.setCustomerWallet(customerOld.getCustomerWallet().add(contractReceivables));
                        customerDbService.updateCustomerById(customerNew);
                        //插入回款表
                        break;
                    }
                    case "4": {
                        customerNew.setCustomerShiftWallet(customerOld.getCustomerShiftWallet().add(contractReceivables));
                        customerDbService.updateCustomerById(customerNew);
                        break;
                    }
/*                case "5": {
                    if (customerOld.getCustomerShiftWallet().compareTo(contractReceivables) == -1) {
                        customerNew.setCustomerShiftWallet(BigDecimal.valueOf(0));
                        customerNew.setCustomerWallet(contractReceivables.subtract(customerOld.getCustomerShiftWallet()));
                    } else {
                        customerNew.setCustomerShiftWallet(customerOld.getCustomerShiftWallet().subtract(contractReceivables));
                    }
                    customerDbService.updateCustomerById(customerNew);
                    break;
                }*/
                    default:
                        break;
                }
            }

            //5、将finish表的产品删除标识设置为1
            finishOrderDBservice.delOrderProductByOrderId(customerContract.getOrderId());
            //如果是补款升级合同，修改原合同已兑换的产品finish表修改成位兑换0:未兑换；1:已兑换
            if("1".equals(customerContract.getContractOtherType())){
                String finishOrderProductId = customerContract.getUpgradeRelateFinishProductId();
                finishOrderDBservice.updateFinishOrderProductExchangeStatus(finishOrderProductId,"0");
            }

            //6、恢复客户关联优惠券使用状态
            List<CustomerContractCoupon> customerContractCouponList = contractCouponDbService.selectContractCouponByContractId(contractId);
            customerContractCouponList.stream().forEach(contractCoupon -> {
                CouponIssued couponIssued = new CouponIssued();
                couponIssued.setReceiveCouponId(contractCoupon.getReceiveCouponId());
                couponIssued.setUsed(Short.parseShort("0"));
                couponIssued.setUpdatePeopleId(userAccount.getAccountId());
                couponIssued.setUpdateTm(new Date());
                couponIssuedDbService.updateCouponIssuedById(couponIssued);
            });

        }
        return jsonObject;
    }

    /**
     * 合同详情(用户系统)--上传补充材料》只有审核处理结果为补充材料;合同状态为审核中的才可以上传
     * 1:上传文件至指定位置;2:文件表(sys_file_upload)新增;3:修改合同表(chs_customer_contract)补充资料附件字段
     * @author yincuimei
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean updateContractReplenishAnnex(CustomerContract customerContract, MultipartFile multipartFile) throws Exception {
        String fileId = "";

        if (multipartFile != null) {

            //保存文件
            fileUploadService.uploadFile(multipartFile, true);
 /*           long time = System.currentTimeMillis();
            String fileName = multipartFile.getOriginalFilename();//原文件名
            String fileType = FilenameUtils.getExtension(fileName).toLowerCase();//文件类型
            String filePath = FileUtil.generateFilePath(time,fileName, PathUtil.getContractPath());
            File file = new File(filePath);
            //上传文件
            multipartFile.transferTo(file);

            String crmIp = PathUtil.getCrmIp();//IP
            String port = PathUtil.getPort();//端口
            String accessPath = PathUtil.getAccessPath();
            String businessPath = PathUtil.getContractPath();//合同相关业务上传路径
            String accessUrl="http://" + crmIp + ":" + port + accessPath + businessPath + time + fileName;//本地运行项目
            // 1: 文件表(sys_file_upload)新增
            fileId = fileUploadService.insertFileUpload(fileName,filePath,accessUrl,fileType);

            //如果文件为word则另存word文件为pdf格式（前端返回pdf文件的绝对路径，下载时使用word文件的绝对路径）
            if(fileName.endsWith("docx")||fileName.endsWith("doc")){
                String filePdfName = fileName.substring(0,fileName.lastIndexOf("."))+".pdf";
                String filePdfPath = FileUtil.generateFilePath(time,filePdfName, PathUtil.getContractPath());
                FileUtil.doc2pdf(filePath,filePdfPath);
            }*/
            // 2: 修改合同表
            UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
            customerContract.setUpdateTm(new Date());//更新时间
            customerContract.setContractReplenishAnnex(fileId);//补充材料文件ID
            return customerContractDbService.updateContractReplenishAnnex(customerContract);
        }
        return false;
    }

    /**
     * 根据客户id查询合同列表
     * @param customerId 客户id
     * @author luojie
     */
    @Override
    public List<CustomerContractVO> selectContractListByCustomerId(String customerId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        List<CustomerContractVO> customerContractVOList = new ArrayList<CustomerContractVO>();
        List<CustomerContract> customerContractList = customerContractDbService.selectContractListByCustomerId(customerId, userAccount.getAccountId());
        customerContractList.stream().forEach(customerContract -> {
            CustomerContractVO customerContractVO = new CustomerContractVO();
            customerContractVO.setContractId(customerContract.getContractId());
            customerContractVO.setContractNumber(customerContract.getContractNumber());
            customerContractVO.setContractStartDate(customerContract.getContractStartDate());
            customerContractVO.setContractEndDate(customerContract.getContractEndDate());
            customerContractVOList.add(customerContractVO);
        });
        return customerContractVOList;
    }


    @Override
    public List<JSONObject> selectContractCoDeveloperById(String contractId) {
        //根据合同id查询合同创建人信息
        List<JSONObject> list = new ArrayList<>();
        CustomerContract customerContract = customerContractDbService.selectContractById(contractId);

       if(customerContract!=null){
           UserAccount userAccount = userAccountService.selectUserAccountByAccountId(customerContract.getCreatePeopleId());
           List<CustomerContractDeveloper> developerList = customerContractDeveloperDbService.selectCustomerContractDeveloperList(contractId);
           developerList.stream().forEach(customerContractDeveloper -> {
               JSONObject jsonObject = new JSONObject();
               jsonObject.put("userName",customerContractDeveloper.getUserName());

               if(userAccount.getUserId().equals(customerContractDeveloper.getCoDeveloper())){
                   return;
               }

               //查询公司名
               SysCompany company = companyService.selectSysCompanyById(customerContractDeveloper.getCompanyId());
               if(company!=null){
                   jsonObject.put("companyName",company.getCompanyName());
               }
               jsonObject.put("allocationMount",customerContractDeveloper.getAllocationMount());
               list.add(jsonObject);
           });
       }
        return list;
    }

    /**
     * 新建合同
     * @param customerContractAddQO 合同添加的QO对象
     * @return
     * @author luojie
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean addContractInformation(CustomerContractAddQO customerContractAddQO) throws ParseException, IOException {
        String contractId = null;
        String contractNumber = null;
        String orderId = null;
        String orderNumber = null;
        Integer couponType = null;
        BigDecimal couponQuota = null;

        //1、新增、编辑合同信息
        JSONObject result = addContract(customerContractAddQO);
        //合同id
        contractId = result.getString("contractId");
        CustomerContract v = customerContractDbService.selectContractById(contractId);
        if(Objects.nonNull(v)){
            ESUtil.syncContractEntity(JSON.parseObject(JSON.toJSONString(v, SerializerFeature.WriteDateUseDateFormat), HashMap.class),ESurl);
        }
        //合同编号
        contractNumber = result.getString("contractNumber");
        if (!StringUtils.isBlank(contractId)) {

            //2、新增、编辑订单
            JSONObject addOrderResult = addContractOrder(customerContractAddQO, contractId, contractNumber);
            orderId = addOrderResult.getString("orderId");
            orderNumber = addOrderResult.getString("orderNumber");

            //3、新增、编辑合作开发人员同时计算合作开发业绩
            addContractDeveloper(customerContractAddQO,customerContractAddQO.getContractActualTotalAmount(), contractId,orderId);
            //4、新增优惠券
            List<ContractCouponQO> couponList = customerContractAddQO.getContractCouponQOList();
            String customerId = customerContractAddQO.getCustomerId();
            if (couponList!=null&&couponList.size()>0) {
                JSONObject coupon = addContractCoupon(contractId, orderId, couponList,customerId);
                couponType = coupon.getInteger("couponType");
                couponQuota = coupon.getBigDecimal("couponQuota");
            }
            //5、新增、更新订单详情表
            if (!StringUtils.isBlank(orderId)) {
                addOrderDetail(customerContractAddQO, orderId,couponType,couponQuota);

            }
            //6、如果是新增合同,更新合同表中订单id
            if (StringUtils.isBlank(customerContractAddQO.getContractId())) {
                CustomerContract customerContract = new CustomerContract();
                customerContract.setContractId(contractId);
                customerContract.setOrderId(orderId);
                customerContractDbService.updateCustomerContract(customerContract);
            }
        }

        //7、插入finish表

        insertFinishOrderProduct(customerContractAddQO,contractNumber,orderId,orderNumber,couponType,couponQuota);
/*        List<FinishOrderProduct> finishList=productOrderDbService.getFinishProductList(orderId);
        if (finishList.size()>0){
            addFinishProductList(finishList,customerContractAddQO.getContractType());
        }*/

        //8、如果不是线下支付，进行扣款，等审核通过后再往回款表中插入数据
        String paymentMethod = customerContractAddQO.getPaymentMethod();
        if(!PaymentMethodEnum.OFFLINE_PAYMENT.getPaymentMethod().equals(paymentMethod)){
            deduction(customerContractAddQO, contractId, contractNumber, orderId);
        }
        return true;
    }
    /***
     * @Description:插入finish表
     * @Param: orderId 订单id
     * @Author: luojie
     * @Date: 2021/9/7 18:46
     */
    public void insertFinishOrderProduct(CustomerContractAddQO customerContractAddQO,String contractNumber,String orderId,String orderNumber,Integer couponType,BigDecimal couponValue){
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        FinishOrderProduct finishOrderProduct = new FinishOrderProduct();
        finishOrderProduct.setContractType(customerContractAddQO.getContractType());
        finishOrderProduct.setProductOrderId(orderId);
        finishOrderProduct.setOrderNumber(orderNumber);
        finishOrderProduct.setContractNumber(contractNumber);
        finishOrderProduct.setCooperateType(customerContractAddQO.getWhetherCooperateDevelopment());
        finishOrderProduct.setSalesmanId(userAccount.getAccountId());
        finishOrderProduct.setCompanyId(userAccount.getCompanyId());
        finishOrderProduct.setCustomerName(customerContractAddQO.getCustomerName());
        finishOrderProduct.setCreatePeopleId(userAccount.getAccountId());
        finishOrderProduct.setCreateTm(new Date());
        finishOrderProduct.setUpdatePeopleId(userAccount.getAccountId());
        finishOrderProduct.setUpdateTm(new Date());

        //1、插入产品
        List<CustomerProductOrderDetail> productOrderDetailList = customerProductOrderDetailDbService.selectCustomerProductOrderDetailList(orderId, "1");
        //查询所有产品的数量
        int productAllCount = 0;
        BigDecimal productAllMount = BigDecimal.ZERO;
        for (CustomerProductOrderDetail customerProductOrderDetail : productOrderDetailList) {
            productAllCount = productAllCount + customerProductOrderDetail.getProductQuantity();
            productAllMount = productAllMount.add(customerProductOrderDetail.getProductFinalPrice().multiply(new BigDecimal(customerProductOrderDetail.getProductQuantity())));
        }

        int count = 1;
        BigDecimal lastCoupon = couponValue;
        for (CustomerProductOrderDetail customerProductOrderDetail : productOrderDetailList) {
            int num = customerProductOrderDetail.getProductQuantity();
            for (int i=0;i<num;i++){
                finishOrderProduct.setFinishOrderProductId(CommonUtils.getGUID());
                finishOrderProduct.setProductId(customerProductOrderDetail.getOrderRelationId());
                finishOrderProduct.setProductName(customerProductOrderDetail.getOrderDetailName());
                finishOrderProduct.setProductOriginalPrice(customerProductOrderDetail.getProductOriginalPrice());
                finishOrderProduct.setProductUnitPrice(customerProductOrderDetail.getProductUnitPrice());

                if(couponType!=null){
                    if(couponType==1){
                        //如果优惠券等于折扣类
                        finishOrderProduct.setProductFinalPrice(customerProductOrderDetail.getProductFinalPrice().multiply(couponValue).setScale(2,BigDecimal.ROUND_HALF_UP));
                    }else if(couponType==2){
                        //如果优惠券等于额度类
                        if(count == productAllCount){
                            if(customerProductOrderDetail.getProductFinalPrice().subtract(lastCoupon).compareTo(BigDecimal.ZERO)<0){
                                finishOrderProduct.setProductFinalPrice(BigDecimal.ZERO);
                            }else{
                                finishOrderProduct.setProductFinalPrice(customerProductOrderDetail.getProductFinalPrice().subtract(lastCoupon));
                            }
                        }else{
                            BigDecimal productFinalPrice =  ((customerProductOrderDetail.getProductFinalPrice().divide(productAllMount,4, RoundingMode.HALF_UP)).multiply(couponValue)).setScale(2,BigDecimal.ROUND_HALF_UP);
                            if(customerProductOrderDetail.getProductFinalPrice().subtract(productFinalPrice).compareTo(BigDecimal.ZERO)<0){
                                finishOrderProduct.setProductFinalPrice(BigDecimal.ZERO);
                            }else{
                                finishOrderProduct.setProductFinalPrice(customerProductOrderDetail.getProductFinalPrice().subtract(productFinalPrice));
                            }
                            lastCoupon = lastCoupon.subtract(productFinalPrice);
                        }
                        count = count + 1;

//                        if(couponValue.compareTo(customerProductOrderDetail.getProductFinalPrice()) > -1){
//                            finishOrderProduct.setProductFinalPrice(BigDecimal.ZERO);
//                            couponValue = couponValue.subtract(customerProductOrderDetail.getProductFinalPrice());
//                        }else{
//                            finishOrderProduct.setProductFinalPrice(customerProductOrderDetail.getProductFinalPrice().subtract(couponValue));
//                            couponValue = BigDecimal.ZERO;
//                        }
                    }
                }else{
                    //没有优惠券
                    finishOrderProduct.setProductFinalPrice(customerProductOrderDetail.getProductFinalPrice());
                }
                finishOrderProduct.setProductMemberPrice(customerProductOrderDetail.getProductMemberPrice());
                //优惠价不存
                finishOrderProduct.setProductCode(customerProductOrderDetail.getProductCode());
                finishOrderProduct.setProductQuantity(customerProductOrderDetail.getProductQuantity());
                finishOrderProduct.setOrderDetailType("1");
                finishOrderProduct.setProductCategories(customerProductOrderDetail.getProductCategories());
                finishOrderProduct.setProductOrderDetailId(customerProductOrderDetail.getProductOrderDetailId());
                finishOrderProduct.setOrderRelationId(customerProductOrderDetail.getOrderRelationId());

                //如果是合作开发，产品号前面加个H
                if ("1".equals(customerContractAddQO.getWhetherCooperateDevelopment())){
                    finishOrderProduct.setFinishOrderProductNum("H" + new Date().getTime()+i);
                }else{
                    finishOrderProduct.setFinishOrderProductNum(String.valueOf(new Date().getTime())+i);
                }
                //业绩换算比例
                BigDecimal ratio = customerMemberProductDbService.selectProductPerformanceRatio(finishOrderProduct.getProductCategories(),finishOrderProduct.getProductId());
                finishOrderProduct.setPerformanceConversionRatio(ratio);
                //Finish表产品号
/*                  if("1".equals(customerProductOrderDetail.getProductCategories())){
                      CustomerMemberProduct customerMemberProduct = customerMemberProductDbService.selectMemberProductById(customerProductOrderDetail.getOrderRelationId());
                      if(customerMemberProduct!=null){
                          finishOrderProduct.setProductStrokesServiceNumber(customerMemberProduct.getServiceNumber());
                      }
                  }*/
                int insertProduct = finishOrderDBservice.insertFinishProduct(finishOrderProduct);
            }
        }

        //2插入活动
        List<CustomerProductOrderDetail> productActivityList = customerProductOrderDetailDbService.selectCustomerProductOrderDetailList(orderId, "2");
        productActivityList.stream().forEach(customerProductOrderDetail -> {
            List<CustomerOrderActivityRelation> customerOrderActivityRelationList = orderActivityRelationDbService.selectOrderActivityRelationByOrderIdAndActivityId(orderId, customerProductOrderDetail.getOrderRelationId());
            customerOrderActivityRelationList.stream().forEach(customerOrderActivityRelation -> {
                //活动没有数量不用循环
                finishOrderProduct.setFinishOrderProductId(CommonUtils.getGUID());
                finishOrderProduct.setProductId(customerOrderActivityRelation.getCustomerProductId());
                finishOrderProduct.setProductName(customerOrderActivityRelation.getProductName());
                finishOrderProduct.setProductOriginalPrice(null);
                finishOrderProduct.setProductUnitPrice(null);
                finishOrderProduct.setProductFinalPrice(customerOrderActivityRelation.getProductFinalPrice());
                finishOrderProduct.setProductMemberPrice(null);
                if ("1".equals(customerOrderActivityRelation.getProductCategories())) {
                    CustomerMemberProduct customerMemberProduct = customerMemberProductDbService.selectMemberProductById(customerOrderActivityRelation.getCustomerProductId());
                    if (customerMemberProduct != null) {
                        finishOrderProduct.setProductCode(customerMemberProduct.getMemberProductCode());
                    }
                } else {
                    CustomerProduct customerProduct = customerProductDbService.selectCustomerProductByProductId(customerOrderActivityRelation.getCustomerProductId());
                    finishOrderProduct.setProductCode(customerProduct.getProductCode());
                }
                //如果是合作开发，产品号前面加个H
                if ("1".equals(customerContractAddQO.getWhetherCooperateDevelopment())){
                    finishOrderProduct.setFinishOrderProductNum("H" + new Date().getTime());
                }else{
                    finishOrderProduct.setFinishOrderProductNum(String.valueOf(new Date().getTime()));
                }
                finishOrderProduct.setProductQuantity(customerProductOrderDetail.getProductQuantity());
                finishOrderProduct.setOrderDetailType("2");
                finishOrderProduct.setProductCategories(customerOrderActivityRelation.getProductCategories());
                finishOrderProduct.setProductOrderDetailId(customerProductOrderDetail.getProductOrderDetailId());
                finishOrderProduct.setOrderRelationId(customerProductOrderDetail.getOrderRelationId());
                //业绩换算比例
                BigDecimal ratio = customerMemberProductDbService.selectProductPerformanceRatio(finishOrderProduct.getProductCategories(), finishOrderProduct.getProductId());
                finishOrderProduct.setPerformanceConversionRatio(ratio);
                int insertProduct = finishOrderDBservice.insertFinishProduct(finishOrderProduct);

            });
        });


        //3、插入赠品
        List<CustomerProductOrderDetail> productGiftList = customerProductOrderDetailDbService.selectCustomerProductOrderDetailList(orderId, "3");
        productGiftList.stream().forEach(customerProductOrderDetail -> {
            List<CustomerOrderGiftRelation> customerOrderGiftRelationList = orderGiftRelationDbService.selectCustomerOrderGiftRelationByOrderIdAndGiftId(orderId, customerProductOrderDetail.getOrderRelationId());
            customerOrderGiftRelationList.stream().forEach(customerOrderGiftRelation -> {
                //赠品活动没有数量不用循环
                finishOrderProduct.setFinishOrderProductId(CommonUtils.getGUID());
                finishOrderProduct.setProductId(customerOrderGiftRelation.getCustomerProductId());
                finishOrderProduct.setProductName(customerOrderGiftRelation.getProductGiftName());
                finishOrderProduct.setProductOriginalPrice(customerOrderGiftRelation.getProductOriginalPrice());
                finishOrderProduct.setProductUnitPrice(customerOrderGiftRelation.getProductUnitPrice());
                finishOrderProduct.setProductFinalPrice(null);
                finishOrderProduct.setProductMemberPrice(null);
                //如果是合作开发，产品号前面加个H
                if ("1".equals(customerContractAddQO.getWhetherCooperateDevelopment())){
                    finishOrderProduct.setFinishOrderProductNum("H" + new Date().getTime());
                }else{
                    finishOrderProduct.setFinishOrderProductNum(String.valueOf(new Date().getTime()));
                }
                if ("1".equals(customerOrderGiftRelation.getProductCategories())) {
                    CustomerMemberProduct customerMemberProduct = customerMemberProductDbService.selectMemberProductById(customerOrderGiftRelation.getCustomerProductId());
                    if (customerMemberProduct != null) {
                        finishOrderProduct.setProductCode(customerMemberProduct.getMemberProductCode());
                    }
                } else {
                    CustomerProduct customerProduct = customerProductDbService.selectCustomerProductByProductId(customerOrderGiftRelation.getCustomerProductId());
                    finishOrderProduct.setProductCode(customerProduct.getProductCode());
                }
                finishOrderProduct.setProductQuantity(customerProductOrderDetail.getProductQuantity());
                finishOrderProduct.setOrderDetailType("3");
                finishOrderProduct.setProductCategories(customerOrderGiftRelation.getProductCategories());
                finishOrderProduct.setProductOrderDetailId(customerProductOrderDetail.getProductOrderDetailId());
                finishOrderProduct.setOrderRelationId(customerProductOrderDetail.getOrderRelationId());

                //业绩换算比例
                BigDecimal ratio = customerMemberProductDbService.selectProductPerformanceRatio(finishOrderProduct.getProductCategories(), finishOrderProduct.getProductId());
                finishOrderProduct.setPerformanceConversionRatio(ratio);
                int insertProduct = finishOrderDBservice.insertFinishProduct(finishOrderProduct);
            });
        });
    }


    /**
     * 同步chs_finish_order_product
     * @param finishList
     */
    public void addFinishProductList(List<FinishOrderProduct> finishList,String contractType){
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        CustomerProductOrder order = productOrderDbService.selectCustomerProductOrderById(finishList.get(0).getProductOrderId());
        CustomerContract contract = customerContractDbService.selectContractById(order.getContractId());
        Customer customer = customerDbService.selectCustomerById(order.getCustomerId());
        for (int i=0;i<finishList.size();i++){
            for (int k=0;k<finishList.get(i).getProductQuantity();k++){
                FinishOrderProduct finishOrderProduct = finishList.get(i);
                finishOrderProduct.setFinishOrderProductId(CommonUtils.getGUID());
                finishOrderProduct.setContractType(contractType);
                finishOrderProduct.setProductOrderId(order.getProductOrderId());
                finishOrderProduct.setOrderNumber(order.getOrderNumber());
                finishOrderProduct.setContractNumber(contract.getContractNumber());

                //业绩换算比例
                BigDecimal ratio = customerMemberProductDbService.selectProductPerformanceRatio(finishOrderProduct.getProductCategories(),finishOrderProduct.getProductId());
                finishOrderProduct.setPerformanceConversionRatio(ratio);

                //如果是合作开发，产品号前面加个H
                if ("1".equals(contract.getWhetherCooperateDevelopment())){
                    finishOrderProduct.setFinishOrderProductNum("H" + new Date().getTime()+i+k);
                    finishOrderProduct.setCooperateType("1");
                }else{
                    finishOrderProduct.setFinishOrderProductNum(String.valueOf(new Date().getTime())+i+k);
                    finishOrderProduct.setCooperateType("0");
                }
                finishOrderProduct.setSalesmanId(order.getCreatePeopleId());
                finishOrderProduct.setCompanyId(order.getAffiliationCompanyId());
                finishOrderProduct.setCustomerName(customer.getCustomerName());
                finishOrderProduct.setCreatePeopleId(userAccount.getAccountId());
                finishOrderProduct.setCreateTm(new Date());
                finishOrderProduct.setUpdatePeopleId(userAccount.getAccountId());
                finishOrderProduct.setUpdateTm(new Date());
                Integer num = finishOrderDBservice.insertFinishProduct(finishOrderProduct);
            }
        }
    }

    //添加优惠券
    public JSONObject addContractCoupon(String contractId, String orderId, List<ContractCouponQO> couponList,String customerId) {
        JSONObject jsonObject = new JSONObject();
        BigDecimal money = BigDecimal.ZERO;
        for (ContractCouponQO coupon : couponList) {
            UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
            CustomerContractCoupon customerContractCoupon = new CustomerContractCoupon();
            customerContractCoupon.setContractCouponId(CommonUtils.getGUID());
            customerContractCoupon.setContractId(contractId);
            customerContractCoupon.setCouponId(coupon.getChsCustomerCouponId());
            customerContractCoupon.setOrderId(orderId);
            customerContractCoupon.setCompanyId(userAccount.getCompanyId());
            customerContractCoupon.setCouponDiscount(coupon.getCouponDiscount());
            customerContractCoupon.setCouponName(coupon.getCouponName());
            customerContractCoupon.setCouponQuota(coupon.getCouponQuota());
            customerContractCoupon.setCouponType((int)coupon.getCouponType());
            customerContractCoupon.setCreateTm(new Date());
            customerContractCoupon.setCreatePeopleId(userAccount.getAccountId());
            customerContractCoupon.setReceiveCouponId(coupon.getReceiveCouponId());
            customerContractCoupon.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
            customerContractCoupon.setCustomerId(customerId);
            contractCouponDbService.insertCustomerCoupon(customerContractCoupon);

            //更新chs_coupon_issued表优惠券使用状态
            CouponIssued couponIssued = new CouponIssued();
            couponIssued.setReceiveCouponId(coupon.getReceiveCouponId());
            couponIssued.setUsed(Short.parseShort("1"));
            couponIssued.setUpdatePeopleId(userAccount.getAccountId());
            couponIssued.setUpdateTm(new Date());
            money = money.add(coupon.getCouponQuota());
            couponIssuedDbService.updateCouponIssuedById(couponIssued);
        }

        if(couponList.size()>0){
            Integer couponType = couponList.get(0).getCouponType();
            jsonObject.put("couponType",couponType);
            if(couponType==1){
                //折扣类
                jsonObject.put("couponQuota",couponList.get(0).getCouponDiscount());
            }else{
                //额度类
                jsonObject.put("couponQuota",money);
            }
        }
        return jsonObject;
    }

    //扣款操作
    public void deduction(CustomerContractAddQO customerContractAddQO, String contractId, String contractNumber, String orderId) {
        String paymentMethod = customerContractAddQO.getPaymentMethod();
        BigDecimal contractReceivables = customerContractAddQO.getContractReceivables();
        Customer customerOld = customerDbService.selectCustomerById(customerContractAddQO.getCustomerId());
        if (StringUtils.isEmpty(paymentMethod)) {
            return;
        }
        //如果支付方式不是线下支付
        if (!PaymentMethodEnum.OFFLINE_PAYMENT.getPaymentMethod().equals(paymentMethod)) {
            Customer customerNew = new Customer();
            customerNew.setCustomerId(customerContractAddQO.getCustomerId());
            //插入回款表
            List<HashMap> returnList = new ArrayList<>();
            //更新客户信息
            //2:线下支付;3:余额支付;4:转入额支付;5:余额＋转入额支付;
            switch (paymentMethod) {
                case "3": {
                    customerNew.setCustomerWallet(customerOld.getCustomerWallet().subtract(contractReceivables));
                    customerDbService.updateCustomerById(customerNew);

/*                    //进行全额回款
                    returnMoney(customerContractAddQO,contractId,orderId);
                    //发送回款消息
                    insertMessage(contractNumber);*/
                    break;
                }
                case "4": {
                    customerNew.setCustomerShiftWallet(customerOld.getCustomerShiftWallet().subtract(contractReceivables));
                    customerDbService.updateCustomerById(customerNew);

/*                    //进行全额回款
                    returnMoney(customerContractAddQO,contractId,orderId);
                    //发送回款消息
                    insertMessage(contractNumber);*/
                    break;
                }
 /*                case "5": {
                    if (customerOld.getCustomerShiftWallet().compareTo(contractReceivables) == -1) {
                        customerNew.setCustomerShiftWallet(BigDecimal.valueOf(0));
                        customerNew.setCustomerWallet(contractReceivables.subtract(customerOld.getCustomerShiftWallet()));
                    } else {
                        customerNew.setCustomerShiftWallet(customerOld.getCustomerShiftWallet().subtract(contractReceivables));
                    }
                    customerDbService.updateCustomerById(customerNew);
                    //存入
                    //转入额
                   HashMap hashMap1 = new HashMap();
                    hashMap1.put("paymentMethod", 4);
                    hashMap1.put("amount", customerOld.getCustomerShiftWallet());
                    returnList.add(hashMap1);
                    //余额
                   HashMap hashMap2 = new HashMap();
                    hashMap2.put("paymentMethod", 2);
                    hashMap2.put("amount", contractReceivables.subtract(customerOld.getCustomerShiftWallet()));
                    returnList.add(hashMap2);
                    insertReturnMoney(returnList, contractId, orderId, customerContractAddQO.getCustomerId(), customerContractAddQO.getContractType());
                    //更新订单，更新合同
                    if ("0".equals(customerContractAddQO.getWhetherCheck())) {
                        updateOrderAndContract(contractId, orderId, contractReceivables);
                    }
                    break;
                }*/
                default:
                    break;
            }

        }
    }



    /***
     * @Description: 根据合同id查询编辑合同页面回显的值
     * @Param:  * @param contractId 合同id
     * @Author: luojie
     * @Date: 2021/3/22 15:11
     */
    @Override
    public CustomerContractEditVO selectCustomerContractEditByContractId(String contractId) {
        CustomerContract customerContract = customerContractDbService.selectContractById(contractId);
        CustomerContractEditVO customerContractEditVO = new CustomerContractEditVO();
        //合同id
        customerContractEditVO.setContractId(customerContract.getContractId());
        //合同类型
        customerContractEditVO.setContractType(customerContract.getContractType());
        //客户id
        customerContractEditVO.setCustomerId(customerContract.getCustomerId());
        //客户名称
        customerContractEditVO.setCustomerName(customerContract.getCustomerName());
        //客户类型
        customerContractEditVO.setCustomerType(customerContract.getCustomerType());
        //联系人id
        customerContractEditVO.setContactId(customerContract.getContactId());
        //合同状态
        customerContractEditVO.setContractStatus(customerContract.getContractStatus());
        //回款状态：0-未回款；1-已回款；3-部分回款
        customerContractEditVO.setPaymentStatus(customerContract.getPaymentStatus());
        //联系人姓名
        customerContractEditVO.setCustomerName(customerContract.getContactName());
        //联系方式
        customerContractEditVO.setContactDetails(customerContract.getContactDetails());
        //客户邮箱
        customerContractEditVO.setCustomerEmail(customerContract.getCustomerEmail());
        //合同续费
        customerContractEditVO.setContractRenewal(customerContract.getContractRenewal());
        //会员主合同
        customerContractEditVO.setMasterMembershipContract(customerContract.getMasterMembershipContract());
        //合同开始时间
        customerContractEditVO.setContractStartDate(customerContract.getContractStartDate());
        //合同结束时间
        customerContractEditVO.setContractEndDate(customerContract.getContractEndDate());
        //回款日期
        customerContractEditVO.setPayBackDate(customerContract.getPayBackDate());
        //付款账号
        customerContractEditVO.setPaymentAccount(customerContract.getPaymentAccount());
        //支付方式
        customerContractEditVO.setPaymentMethod(customerContract.getPaymentMethod());
        //跟进记录id
        customerContractEditVO.setFollowRecordId(customerContract.getFollowRecordId());
        //商机id
        customerContractEditVO.setOpportunityId(customerContract.getOpportunityId());
        //审核是否加盖公章
        customerContractEditVO.setApplyElectronicContract(customerContract.getApplyElectronicContract());
        //合同实际总金额
        customerContractEditVO.setContractActualTotalAmount(customerContract.getContractActualTotalAmount());
        //合同总金额
        customerContractEditVO.setContractTotalAmount(customerContract.getContractTotalAmount());
        //合同优惠总金额
        customerContractEditVO.setContractDiscountTotalAmount(customerContract.getContractDiscountTotalAmount());
        //合同应收款
        customerContractEditVO.setContractReceivables(customerContract.getContractReceivables());
        //是否保密
        customerContractEditVO.setWhetherKeepSecret(customerContract.getWhetherKeepSecret());
        //提前/延期原因
        customerContractEditVO.setAdvancePostponementReason(customerContract.getAdvancePostponementReason());
        //合同审核备注
        customerContractEditVO.setContractReviewNotes(customerContract.getContractReviewNotes());
        //合同审核状态
        customerContractEditVO.setContractReviewStatus(customerContract.getContractReviewStatus());
        //合同附件上传id
        FileUpload fileUploadAnnexId = fileUploadService.selectFileUploadById(customerContract.getContractAnnexId());
        if (fileUploadAnnexId != null) {
            customerContractEditVO.setContractAnnexId(customerContract.getContractAnnexId());
            customerContractEditVO.setContractAnnexAccessUrl(fileUploadAnnexId.getAccessUrl());
        }
        //审核附件id
        FileUpload fileUploadReviewAnnexId = fileUploadService.selectFileUploadById(customerContract.getReviewAnnexId());
        if (fileUploadReviewAnnexId != null) {
            customerContractEditVO.setReviewAnnexId(customerContract.getReviewAnnexId());
            customerContractEditVO.setReviewAnnexAccessUrl(fileUploadReviewAnnexId.getAccessUrl());
        }
        //给合同开发人员赋值
        List<CustomerContractDeveloper> developerList = customerContractDeveloperDbService.selectCustomerContractDeveloperList(contractId);
        List<HashMap> mapList = new ArrayList<>();
        developerList.stream().forEach(customerContractDeveloper -> {
            //可以查到合作开发人员
            UserAccount account = userAccountService.selectUserAccountByAccountId(customerContractDeveloper.getCoDeveloper());
            if (account != null) {
                HashMap developer = new HashMap();
                developer.put("userId", account.getAccountId());
                developer.put("userName", account.getUserName());
                //查询用户电话
                UserInfo userInfo = userInfoDbService.selectUserInfoByUserId(account.getUserId());
                if (userInfo != null) {
                    developer.put("userContact", userInfo.getUserContact());
                }
                mapList.add(developer);
            }
        });
        customerContractEditVO.setCoDeveloperList(mapList);
        //给订单赋值
        CustomerProductOrder productOrder = customerProductOrderDbService.selectProductOrderByContractId(customerContract.getContractId());
        CustomerProductOrderEditVO orderEditVO = new CustomerProductOrderEditVO();
        orderEditVO.setProductOrderId(productOrder.getProductOrderId());
        orderEditVO.setOrderActualTotalAmount(productOrder.getOrderActualTotalAmount());
        orderEditVO.setOrderDiscountTotalAmount(productOrder.getOrderDiscountTotalAmount());
        orderEditVO.setOrderTotalAmount(productOrder.getOrderTotalAmount());
        orderEditVO.setOrderSurcharge(productOrder.getOrderSurcharge());
        orderEditVO.setOrderSurchargeRemark(productOrder.getOrderSurchargeRemark());
        customerContractEditVO.setProductOrder(orderEditVO);
        //获取订单产品列表
        List<CustomerProductOrderDetail> productOrderDetailList = customerProductOrderDetailDbService.selectCustomerProductOrderDetailList(productOrder.getProductOrderId(), "1");
        List<CustomerProductOrderDetailEditVO> customerProductEditVOList = new ArrayList();
        productOrderDetailList.stream().forEach(customerProductOrderDetail -> {
            CustomerProductOrderDetailEditVO productEditVO = new CustomerProductOrderDetailEditVO();
            productEditVO.setProductOrderDetailId(customerProductOrderDetail.getProductOrderDetailId());
            productEditVO.setProductName(customerProductOrderDetail.getOrderDetailName());
            productEditVO.setProductCode(customerProductOrderDetail.getProductCode());
            productEditVO.setProductCategories(customerProductOrderDetail.getProductCategories());
            productEditVO.setProductOriginalPrice(customerProductOrderDetail.getProductOriginalPrice());
            productEditVO.setProductUnitPrice(customerProductOrderDetail.getProductUnitPrice());
            productEditVO.setProductMemberPrice(customerProductOrderDetail.getProductMemberPrice());
            productEditVO.setProductDiscountPrice(customerProductOrderDetail.getProductPreferentialPrice());
            productEditVO.setProductFinalPrice(customerProductOrderDetail.getProductFinalPrice());
            productEditVO.setProductNumber(customerProductOrderDetail.getProductQuantity());
            productEditVO.setProductCode(customerProductOrderDetail.getProductCode());
            productEditVO.setCustomerProductId(customerProductOrderDetail.getOrderRelationId());
            customerProductEditVOList.add(productEditVO);
        });
        customerContractEditVO.setProductEditArr(customerProductEditVOList);
        //获取订单活动产品列表
        List<CustomerActivityOrderDetailEditVO> activityOrderDetailEditVOList = new ArrayList();
        List<CustomerProductOrderDetail> productActivityList = customerProductOrderDetailDbService.selectCustomerProductOrderDetailList(productOrder.getProductOrderId(), "2");
        productActivityList.stream().forEach(productOrderDetail -> {
            CustomerActivityOrderDetailEditVO activityOrderDetailEditVO = new CustomerActivityOrderDetailEditVO();
            activityOrderDetailEditVO.setProductOrderDetailId(productOrderDetail.getProductOrderDetailId());
            activityOrderDetailEditVO.setProductActivityName(productOrderDetail.getOrderDetailName());
            activityOrderDetailEditVO.setActivityPrice(productOrderDetail.getProductOriginalPrice());
            activityOrderDetailEditVO.setActivityDiscountPrice(productOrderDetail.getProductPreferentialPrice());
            activityOrderDetailEditVO.setProductFinalPrice(productOrderDetail.getProductFinalPrice());
            activityOrderDetailEditVO.setActivityNumber(productOrderDetail.getProductQuantity());
            activityOrderDetailEditVO.setProductActivityId(productOrderDetail.getOrderRelationId());
            List<CustomerOrderActivityRelation> orderActivityRelationList = orderActivityRelationDbService.selectOrderActivityRelationByOrderIdAndActivityId(productOrder.getProductOrderId(), productOrderDetail.getOrderRelationId());
            List<JSONObject> productList = new ArrayList<>();
            Boolean ifMemberActivity = false;
            for (CustomerOrderActivityRelation customerOrderActivityRelation : orderActivityRelationList) {
                JSONObject product = new JSONObject();
                product.put("productId", customerOrderActivityRelation.getCustomerProductId());
                product.put("productName", customerOrderActivityRelation.getProductName());
                if ("1".equals(customerOrderActivityRelation.getProductCategories())) {
                    ifMemberActivity = true;
                }
                productList.add(product);
            }
            activityOrderDetailEditVO.setIfMemberActivity(ifMemberActivity);
            activityOrderDetailEditVO.setProductList(productList);
            activityOrderDetailEditVOList.add(activityOrderDetailEditVO);
        });
        customerContractEditVO.setProductActivityEditArr(activityOrderDetailEditVOList);
        //获取订单赠品列表
        List<CustomerProductOrderDetail> productGiftActivityList = customerProductOrderDetailDbService.selectCustomerProductOrderDetailList(productOrder.getProductOrderId(), "3");
        List<CustomerProductGiftActivityContractVO> productGiftActivityContractVOList = new ArrayList<>();
        productGiftActivityList.stream().forEach(productOrderDetail -> {
            CustomerProductGiftActivityContractVO productGiftActivityContractVO = new CustomerProductGiftActivityContractVO();
            productGiftActivityContractVO.setProductGiftActivityId(productOrderDetail.getOrderRelationId());
            productGiftActivityContractVO.setGiftActivityName(productOrderDetail.getOrderDetailName());
            //关联赠品活动表查询赠品活动信息
            CustomerProductGiftActivity customerProductGiftActivity = productGiftActivityDbService.selectProductGiftActivityById(productOrderDetail.getOrderRelationId());
            CustomerProduct customerProduct = customerProductDbService.selectCustomerProductByProductId(customerProductGiftActivity.getCustomerProductId());
            if (customerProduct != null) {
                productGiftActivityContractVO.setProductName(customerProduct.getProductName());
            }
            if ("1".equals(customerProductGiftActivity.getGiftCategory())) {
                productGiftActivityContractVO.setGiftCategoryName("产品类");
            } else {
                productGiftActivityContractVO.setGiftCategoryName("价格类");
            }
            productGiftActivityContractVO.setGiftCategory(customerProductGiftActivity.getGiftCategory());
            productGiftActivityContractVO.setGiftActivityPriceStart(customerProductGiftActivity.getGiftActivityPriceStart());
            productGiftActivityContractVO.setGiftActivityPriceEnd(customerProductGiftActivity.getGiftActivityPriceEnd());
            productGiftActivityContractVO.setGiftPeriodValidityStart(customerProductGiftActivity.getGiftPeriodValidityStart());
            productGiftActivityContractVO.setGiftPeriodValidityEnd(customerProductGiftActivity.getGiftPeriodValidityEnd());
            List<HashMap> productList = new ArrayList<>();
            List<CustomerOrderGiftRelation> customerOrderGiftRelationList = customerOrderGiftRelationDbService.selectCustomerOrderGiftRelationByOrderIdAndGiftId(productOrder.getProductOrderId(), productOrderDetail.getOrderRelationId());
            for (CustomerOrderGiftRelation customerOrderGiftRelation : customerOrderGiftRelationList) {
                HashMap map = new HashMap();
                map.put("productId", customerOrderGiftRelation.getCustomerProductId());
                map.put("productName", customerOrderGiftRelation.getProductGiftName());
                map.put("productOriginalPrice", customerOrderGiftRelation.getProductOriginalPrice());
                map.put("productUnitPrice", customerOrderGiftRelation.getProductUnitPrice());
                productList.add(map);
            }
            productGiftActivityContractVO.setGiftProductList(productList);
            productGiftActivityContractVOList.add(productGiftActivityContractVO);
        });
        customerContractEditVO.setGiftEditArr(productGiftActivityContractVOList);
        return customerContractEditVO;
    }

    /**
     * 联系人详情-订单合同-通过联系人id
     *
     * @param pageIndex      页码
     * @param pageSize       分页大小
     * @param sortName       排序列名字
     * @param sortOrder      排序
     * @param contactId      联系人id
     * @param contractNumber 合同编号
     * @return
     */
    @Override
    public DhPageInfo<ContactDetailByCustomerContractVO> selectCustomerContractByContactId(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String contactId, String contractNumber) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("ccc.create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }

        List<ContactDetailByCustomerContractVO> list = customerContractDbService.selectCustomerContractByContactId(contactId, contractNumber, order.toString());

        PageInfo<ContactDetailByCustomerContractVO> pageInfo = new PageInfo<ContactDetailByCustomerContractVO>(list);
        return new DhPageInfo<ContactDetailByCustomerContractVO>(pageInfo, list);
    }

    /**
     * @return
     * @Description:商机添加合同赋值
     * @Param: * @param customerContractAddQO 添加合同赋值
     */
    @Override
    public CustomerContractEditVO opportunityContractDetail(String opportunityId, String contractType) {

        CustomerContractEditVO contractVO = new CustomerContractEditVO();
        OpportunityContractDetailVO opportunityContractDetailVO = opportunityDbService.opportunityContractDetail(opportunityId);

        contractVO.setContractType(contractType);  //合同类型
        contractVO.setCustomerId(opportunityContractDetailVO.getCustomerId());
        contractVO.setCustomerName(opportunityContractDetailVO.getCustomerName());
        contractVO.setCustomerType(opportunityContractDetailVO.getCustomerType());
        contractVO.setCustomerEmail(opportunityContractDetailVO.getEmail());
        contractVO.setContactId(opportunityContractDetailVO.getContactId());
        contractVO.setContactName(opportunityContractDetailVO.getContactName());
        contractVO.setContactDetails(opportunityContractDetailVO.getContactInformation());
        contractVO.setOpportunityId(opportunityContractDetailVO.getOpportunityId());
        contractVO.setOpportunityTitle(opportunityContractDetailVO.getOpportunityTitle());

        //查询联系人最新的一条跟进记录
        List<ClueFollow> list = clueFollowService.getClueFollowByContactId(opportunityContractDetailVO.getContactId());
        if (list.size() > 0) {
            ClueFollow clueFollow = list.get(0);
            contractVO.setFollowRecordId(clueFollow.getClueFollowId());
            contractVO.setFollowWay(clueFollow.getFollowWay());
            contractVO.setFollowTm(clueFollow.getFollowTm());
        }

        //合作开发人员
        List<OpportunityCollaborator> opportunityCollaborators = opportunityCollaboratorService.opportunityCollaboratorList(opportunityId);
        contractVO.setOpportunityCollaboratorList(opportunityCollaborators);

        return contractVO;
    }


    /**
     * 添加合同
     *
     * @param customerContractAddQO
     * @return
     * @author luojie
     */
    public JSONObject addContract(CustomerContractAddQO customerContractAddQO){
        JSONObject jsonObject = new JSONObject();
        String contractId = customerContractAddQO.getContactId();
        CustomerContract customerContract = new CustomerContract();
        //所属分公司
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        //合同id
        contractId = CommonUtils.getGUID();
        customerContract.setContractId(contractId);
        //合同编号
        Random rand = new Random();
        int k = rand.nextInt(999);
        String contractNumber = "C" + new Date().getTime() + k;
        customerContract.setContractNumber(contractNumber);
        customerContract.setCustomerId(customerContractAddQO.getCustomerId());
        customerContract.setCustomerName(customerContractAddQO.getCustomerName());
        customerContract.setCustomerType(customerContractAddQO.getCustomerType());
        customerContract.setContractType(customerContractAddQO.getContractType());
        customerContract.setContractStartDate(customerContractAddQO.getContractNewStartDate());
        customerContract.setContractEndDate(customerContractAddQO.getContractNewEndDate());
        customerContract.setPayBackDate(customerContractAddQO.getPayBackDate());
        customerContract.setPaymentAccount(customerContractAddQO.getPaymentAccount());
        customerContract.setContractActualTotalAmount(customerContractAddQO.getContractActualTotalAmount());
        //不是老合同
        customerContract.setOldContract("0");
        //合同开发人员
        List<ContractCoDeveloperQO> coDeveloperList = customerContractAddQO.getCoDeveloperList();
        if (coDeveloperList != null && coDeveloperList.size()>0) {
            customerContract.setWhetherCooperateDevelopment("1");
            customerContractAddQO.setWhetherCooperateDevelopment("1");
        } else {
            customerContract.setWhetherCooperateDevelopment("0");
            customerContractAddQO.setWhetherCooperateDevelopment("0");
        }

        //如果是续费合同需要判断合同的类型
        String contractType = customerContractAddQO.getContractType();
        //合同会员类型1:非会员合同：会员类型一定是非会员0 2:会员新单合同、4:续费合同 合同会员类型为会员1；3:活动合同不一定是会员合同还是非会员合同
        if ("2".equals(contractType) || "4".equals(contractType)) {
            customerContract.setWhetherCheck("1");
            customerContractAddQO.setWhetherCheck("1");
        } else if ("3".equals(contractType)) {
            Boolean whetherCheck = false;
            //查询合同下活动列表，若此合同的活动下有一个活动是会员活动，则此合同为会员合同
            List<CustomerActivityProductAddQO> customerActivityProductAddQOList = customerContractAddQO.getCustomerActivityProductAddQOList();
            for (CustomerActivityProductAddQO customerActivityProductAddQO : customerActivityProductAddQOList) {
                if (customerActivityProductAddQO.getIfMemberActivity()) {
                    whetherCheck = true;
                }
            }
            if (whetherCheck) {
                customerContract.setWhetherCheck("1");
                customerContractAddQO.setWhetherCheck("1");
            } else {
                customerContract.setWhetherCheck("0");
                customerContractAddQO.setWhetherCheck("0");
            }

        } else {
            customerContract.setWhetherCheck("0");
            customerContractAddQO.setWhetherCheck("0");
        }


        //如果合同类型为合同续费，需要判断续费类型是提前续费合同还是延期续费合同
        //(没到合同结束日期是提前续费，到了合同日期没超过3个月是延期续费，超过3个月是新单合同)
        if ("4".equals(contractType)) {
            if ((new Date()).getTime() < customerContractAddQO.getContractOldEndDate().getTime()) {
                //合同提前续费
                customerContract.setContractRenewal("2");
            }/*else if (DateUtils.isOutOfDate(new Date(), customerContractAddQO.getContractOldEndDate())) {
                //会员新单合同
                customerContract.setContractType("2");
                //合同续费为正常合同
                customerContract.setContractRenewal("1");
            } */ else {
                //合同延期续费
                customerContract.setContractRenewal("3");
            }
        }

        //更新客户表客户状态
        if ("2".equals(contractType)) {
            //新单合同
            Customer customer = new Customer();
            customer.setCustomerId(customerContractAddQO.getCustomerId());
            customer.setNewOrderRenewalCustomer(0);
            customerDbService.updateCustomerById(customer);

        } else if ("4".equals(contractType)) {
            //续费合同
            Customer customer = new Customer();
            customer.setCustomerId(customerContractAddQO.getCustomerId());
            customer.setNewOrderRenewalCustomer(1);
            customerDbService.updateCustomerById(customer);
        }

        customerContract.setAffiliationCompanyId(userAccount.getCompanyId());
        customerContract.setMasterMembershipContract(customerContractAddQO.getMasterMembershipContract());
        customerContract.setPaymentMethod(customerContractAddQO.getPaymentMethod());
        customerContract.setContactId(customerContractAddQO.getContactId());
        customerContract.setContactName(customerContractAddQO.getContactName());
        customerContract.setContactDetails(customerContractAddQO.getContactDetails());
        customerContract.setCustomerEmail(customerContractAddQO.getCustomerEmail());
        customerContract.setContractAnnexId(customerContractAddQO.getContractAnnexId());
        customerContract.setReviewAnnexId(customerContractAddQO.getReviewAnnexId());
        customerContract.setContractTotalAmount(customerContractAddQO.getContractTotalAmount());
        customerContract.setContractDiscountTotalAmount(customerContractAddQO.getContractDiscountTotalAmount());
        customerContract.setApplyElectronicContract(customerContractAddQO.getApplyElectronicContract());
        customerContract.setOpportunityId(customerContractAddQO.getOpportunityId());
        customerContract.setFollowRecordId(customerContractAddQO.getFollowRecordId());
        customerContract.setContractReceivables(customerContractAddQO.getContractReceivables());
        customerContract.setContractReviewNotes(customerContractAddQO.getContractReviewNotes());
        customerContract.setWhetherKeepSecret(customerContractAddQO.getWhetherKeepSecret());
        //审核状态
        customerContract.setContractReviewStatus("0");

        //合同是否特批(需要审核就是特批1，不需要审核就不是特批0)
        //如果合同不是余额支付且没有上传附件
/*        if (!PaymentMethodEnum.BALANCE_PAYMENT.getPaymentMethod().equals(customerContractAddQO.getPaymentMethod())) {
            if(StringUtils.isBlank(customerContractAddQO.getReviewAnnexId())){
                customerContract.setSpecialApprovalStatus("0");
            }else {
                customerContract.setSpecialApprovalStatus("1");
            }
        } else {
            customerContract.setSpecialApprovalStatus("1");
        }*/
        Boolean reviewed = false;
        if (!PaymentMethodEnum.BALANCE_PAYMENT.getPaymentMethod().equals(customerContractAddQO.getPaymentMethod())&&
                ContractTypeEnum.NON_MEMBER_CONTRACT.getContractTypeCode().equals(contractType)) {
            //计算非会员合同需要审核的产品
            int reviewCount = 0;
            List<CustomerContractProductAddQO> customerContractProductAddQOList = customerContractAddQO.getCustomerContractProductAddQOList();
            for (int i = 0; i < customerContractProductAddQOList.size(); i++) {
                if(customerContractProductAddQOList.get(i).getProductFinalPrice()!=null&&
                        customerContractProductAddQOList.get(i).getProductOriginalPrice()!=null){
                    if(customerContractProductAddQOList.get(i).getProductFinalPrice().compareTo(customerContractProductAddQOList.get(i).getProductMemberPrice())>-1){
                        reviewCount = reviewCount+1;
                    }
                }
            }
            //审核产品数量等于总产品数量，则此合同需要审核
            if(customerContractProductAddQOList.size()>0 && reviewCount == customerContractProductAddQOList.size()){
                reviewed = true;
            }
        }

        //需要系统审核
        if(reviewed){
            //审核表中插入一条记录
            Date date = new Date();
            ContractReview contractReview = new ContractReview();
            contractReview.setContractReviewId(CommonUtils.getGUID());
            contractReview.setContractId(customerContract.getContractId());
            contractReview.setProcessResult("2");
            //如果合同审批结果
            contractReview.setContractReviewNotes("系统审核通过");
            contractReview.setCreatePeopleId("18376c1f9b684929a11ea6b335d246bc");
            contractReview.setCreateTm(date);
            Boolean result = contractReviewDbService.addContractReview(contractReview);

            //合同审核增加审核信息
            customerContract.setSpecialApprovalStatus("0");
            customerContract.setContractReviewStatus("2");
            customerContract.setContractReviewNotes("系统审核通过");
            customerContract.setReviewerId("18376c1f9b684929a11ea6b335d246bc");
            customerContract.setReviewerName("系统审核");
            customerContract.setReviewTime(date);

            //插入消息表信息
            MessagePrompt messagePrompt = new MessagePrompt();
            messagePrompt.setMessageId(CommonUtils.getGUID());
            //消息类型为审核
            messagePrompt.setMessageType(Short.parseShort("3"));
            messagePrompt.setMessageState(Short.parseShort("0"));
            String processResultValue = "";
            processResultValue = "审核通过";
            messagePrompt.setMessageContent("您的合同编号" + contractNumber  + "已审批，结果：" + processResultValue);
            messagePrompt.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
            messagePrompt.setCreatePeopleId(userAccount.getAccountId());
            messagePrompt.setCreateTm(new Date());
            messagePrompt.setUpdatePeopleId(userAccount.getAccountId());
            messagePrompt.setUpdateTm(new Date());
            messagePromptDbService.insertMessagePrompt(messagePrompt);

        }else{
            //判断是否需要客服审核
            if (!PaymentMethodEnum.BALANCE_PAYMENT.getPaymentMethod().equals(customerContractAddQO.getPaymentMethod())) {
                if(customerContractAddQO.getContractDiscountTotalAmount()!=null){
                    if(customerContractAddQO.getContractDiscountTotalAmount().compareTo(BigDecimal.ZERO)==1){
                        customerContract.setSpecialApprovalStatus("1");
                    }else {
                        customerContract.setSpecialApprovalStatus("0");
                    }
                }
            } else {
                customerContract.setSpecialApprovalStatus("1");
            }
        }

        //如果合同类型是7会员单次合同,则重新赋合同值
        if ("7".equals(customerContractAddQO.getContractType())) {
            customerContract.setContractTotalAmount(customerContractAddQO.getContractReceivables());
            customerContract.setContractActualTotalAmount(customerContractAddQO.getContractReceivables());
            customerContract.setContractDiscountTotalAmount(BigDecimal.ZERO);
            customerContract.setSpecialApprovalStatus("0");
            if(!StringUtils.isBlank(customerContractAddQO.getPaymentMethod())&&
                    PaymentMethodEnum.BALANCE_PAYMENT.getPaymentMethod().equals(customerContractAddQO.getPaymentMethod())){
                customerContract.setWhetherCheck("1");
                customerContractAddQO.setWhetherCheck("1");
            }
        }


        customerContract.setUpdatePeopleId(userAccount.getAccountId());
        customerContract.setUpdateTm(new Date());

        //合同状态:1-未生效；2-生效中；3-已结束；4-已作废；5-意外终止；6-挂起
        customerContract.setContractStatus("1");
        //删除状态
        customerContract.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        //锁定状态
        customerContract.setLockedState("0");
        //回款状态
        customerContract.setPaymentStatus("0");
        //审批状态
        customerContract.setContractApprovalStatus("0");

        //提成发放状态--1:已全部发放；2:部分发放;3:未发放
        customerContract.setCommissionStatus("3");
        //是否挂起
        customerContract.setWhetherHang("0");
        //创建人
        customerContract.setCreatePeopleId(userAccount.getAccountId());
        //创建时间
        customerContract.setCreateTm(new Date());

        //判断合同分类是否为空
        if (customerContractAddQO.getContractCategory() != null) {
            customerContract.setContractCategory(customerContractAddQO.getContractCategory());
        }

        //新增合同
        Boolean result = customerContractDbService.insertCustomerContract(customerContract);
        if(result&&!StringUtils.isBlank(customerContractAddQO.getOpportunityId())){
            //修改商机表中商机合同
            Opportunity opportunity = new Opportunity();
            opportunity.setOpportunityId(customerContractAddQO.getOpportunityId());
            opportunity.setOpportunityContractType("1");
            opportunity.setUpdateTm(new Date());
            opportunity.setUpdatePeopleId(userAccount.getAccountId());
            opportunityDbService.updateOpportunityId(opportunity);
        }



        jsonObject.put("contractId", customerContract.getContractId());
        jsonObject.put("contractNumber", customerContract.getContractNumber());

        return jsonObject;
    }

    /**
     * 新增合同开发人员
     *
     * @param customerContractAddQO 新增对象
     * @param contractId            新增合同id
     * @author luojie
     */
    public void addContractDeveloper(CustomerContractAddQO customerContractAddQO,BigDecimal contractActualTotalAmount, String contractId,String orderId) {
        //合同实际总金额
        BigDecimal contractReceivables = customerContractAddQO.getContractActualTotalAmount();

        List<ContractCoDeveloperQO> coDeveloperList = customerContractAddQO.getCoDeveloperList();
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        if(coDeveloperList!=null && coDeveloperList.size()>0){
            for (ContractCoDeveloperQO contractCoDeveloperQO : coDeveloperList) {
                //如果合作开发人员的用户id为空则不进行保存
                if(StringUtils.isBlank(contractCoDeveloperQO.getUserId())){
                    continue;
                }

                CustomerContractDeveloper customerContractDeveloper = new CustomerContractDeveloper();
                UserAccount userAccount1 = userAccountService.selectUserAccountByAccountId(contractCoDeveloperQO.getUserId());

                if(userAccount1==null){
                    continue;
                }
                customerContractDeveloper.setCoDeveloper(userAccount1.getUserId());
                customerContractDeveloper.setContractDeveloperId(CommonUtils.getGUID());
                customerContractDeveloper.setContractId(contractId);
                customerContractDeveloper.setOrderId(orderId);

                customerContractDeveloper.setUserName(contractCoDeveloperQO.getUserName());
                customerContractDeveloper.setCompanyId(contractCoDeveloperQO.getCompanyId());
                customerContractDeveloper.setCreateTm(new Date());
                customerContractDeveloper.setCreatePeopleId(userAccount.getAccountId());
                customerContractDeveloper.setAllocationMount(contractCoDeveloperQO.getAllocationMount());
                customerContractDeveloper.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
                //计算合同合作开发分配比例
                BigDecimal allocationRatio = contractCoDeveloperQO.getAllocationMount().divide(contractActualTotalAmount,5,BigDecimal.ROUND_DOWN);
                customerContractDeveloper.setAllocationRatio(allocationRatio);
                customerContractDeveloperDbService.insertCustomerContractDeveloper(customerContractDeveloper);
                if(contractCoDeveloperQO.getAllocationMount()!=null){
                    contractReceivables = contractReceivables.subtract(contractCoDeveloperQO.getAllocationMount());
                }

            }

            //如果给自己最后分配的份额不为0，则最后再保存创建人自己
            if(contractReceivables!=BigDecimal.ZERO){
                CustomerContractDeveloper customerContractDeveloper = new CustomerContractDeveloper();
                customerContractDeveloper.setContractDeveloperId(CommonUtils.getGUID());
                customerContractDeveloper.setContractId(contractId);
                customerContractDeveloper.setOrderId(orderId);
                customerContractDeveloper.setCoDeveloper(userAccount.getUserId());
                customerContractDeveloper.setUserName(userAccount.getUserName());
                customerContractDeveloper.setCompanyId(userAccount.getCompanyId());
                customerContractDeveloper.setCreateTm(new Date());
                customerContractDeveloper.setCreatePeopleId(userAccount.getAccountId());
                customerContractDeveloper.setAllocationMount(contractReceivables);
                customerContractDeveloper.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
                //计算合同合作开发分配比例
                BigDecimal allocationRatio = contractReceivables.divide(contractActualTotalAmount,5,BigDecimal.ROUND_DOWN);
                customerContractDeveloper.setAllocationRatio(allocationRatio);
                customerContractDeveloperDbService.insertCustomerContractDeveloper(customerContractDeveloper);
            }
        }
    }

    /**
     * 添加订单
     *
     * @param customerContractAddQO
     * @param contractId            合同id
     * @param contractNumber        合同编号
     * @return
     * @author luojie
     */
    public JSONObject addContractOrder(CustomerContractAddQO customerContractAddQO, String contractId, String contractNumber) {
        JSONObject result = new JSONObject();
        String orderId = CommonUtils.getGUID();
        CustomerProductOrder customerProductOrder = new CustomerProductOrder();
        customerProductOrder.setProductOrderId(orderId);
        //订单类型(根据合同里面的会员类型来判断)--0:非会员订单;1:会员订单
        customerProductOrder.setOrderType(customerContractAddQO.getWhetherCheck());
        customerProductOrder.setOrderPaymentWay(customerContractAddQO.getPaymentMethod());
        customerProductOrder.setOrderDiscountTotalAmount(customerContractAddQO.getContractDiscountTotalAmount());
        customerProductOrder.setOrderActualTotalAmount(customerContractAddQO.getContractActualTotalAmount());
        customerProductOrder.setOrderTotalAmount(customerContractAddQO.getContractTotalAmount());
        customerProductOrder.setOrderSurcharge(customerContractAddQO.getOrderSurcharge());
        customerProductOrder.setOrderSurchargeRemark(customerContractAddQO.getOrderSurchargeRemark());
        customerProductOrder.setContactPerson(customerContractAddQO.getContactName());
        customerProductOrder.setBindMobilePhoneNumber(customerContractAddQO.getContactDetails());
        customerProductOrder.setCustomerEmail(customerContractAddQO.getCustomerEmail());
        customerProductOrder.setContractType(customerContractAddQO.getContractType());
        //是否合作开发
        customerProductOrder.setWhetherCoDevelopment(customerContractAddQO.getWhetherCooperateDevelopment());

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        customerProductOrder.setUpdatePeopleId(userAccount.getAccountId());
        customerProductOrder.setUpdateTm(new Date());
        customerProductOrder.setAffiliationCompanyId(userAccount.getCompanyId());
        customerProductOrder.setCustomerId(customerContractAddQO.getCustomerId());
        customerProductOrder.setCustomerName(customerContractAddQO.getCustomerName());
        //不是老订单
        customerProductOrder.setOldOrder("0");

        //如果合同类型是7会员单次合同,则重新赋合同值
        if ("7".equals(customerContractAddQO.getContractType())) {
            customerProductOrder.setOrderActualTotalAmount(customerContractAddQO.getContractReceivables());
            customerProductOrder.setOrderTotalAmount(customerContractAddQO.getContractReceivables());
            customerProductOrder.setOrderDiscountTotalAmount(BigDecimal.ZERO);
        }


        //订单编码
        Random rand = new Random();
        int k = rand.nextInt(999);
        String orderNumber = "D" + new Date().getTime()+ k;
        customerProductOrder.setOrderNumber(orderNumber);
        //是否挂起--1:是;2-否
        customerProductOrder.setWhetherSuspend("2");
        //订单状态--1:等待回款;2:已完成;3:作废
        customerProductOrder.setOrderStatus("1");
        customerProductOrder.setCreatePeopleId(userAccount.getAccountId());
        customerProductOrder.setCreateTm(new Date());
        customerProductOrder.setContractId(contractId);
        customerProductOrder.setContractNumber(contractNumber);
        //新增订单
        Boolean insertResult = customerProductOrderDbService.insertProductOrder(customerProductOrder);
        result.put("orderNumber",orderNumber);
        result.put("orderId",orderId);
        return result;
    }

    /**
     * 新增订单明细
     *
     * @param customerContractAddQO
     * @param orderId               订单Id
     * @return
     * @author luojie
     */
    public Boolean addOrderDetail(CustomerContractAddQO customerContractAddQO, String orderId,Integer couponType,BigDecimal couponValue) {
/*        if (!StringUtils.isBlank(customerContractAddQO.getContractId())) {
            //编辑合同，删除订单明细
            customerProductOrderDetailDbService.deleteProductOrderDetailListByOrderId(orderId);
            //删除活动-产品关系表
            orderActivityRelationDbService.deleteOrderActivityRelationByOrderId(orderId);
            //删除赠品-产品关系表
            orderGiftRelationDbService.deleteCustomerOrderGiftRelationByOrderId(orderId);
        }*/

        List<CustomerContractProductAddQO> customerContractProductAddQOList = customerContractAddQO.getCustomerContractProductAddQOList();
        //产品不为空添加产品
        //产品不为空添加产品
        if (customerContractProductAddQOList.size() > 0) {
            customerContractProductAddQOList.stream().forEach(customerContractProductAddQO -> {
                CustomerProductOrderDetail customerProductOrderDetail = new CustomerProductOrderDetail();
                customerProductOrderDetail.setProductOrderDetailId(CommonUtils.getGUID());
                customerProductOrderDetail.setOrderDetailName(customerContractProductAddQO.getProductName());
                customerProductOrderDetail.setProductCode(customerContractProductAddQO.getProductCode());
                customerProductOrderDetail.setProductCategories(customerContractProductAddQO.getProductCategories());
                customerProductOrderDetail.setProductOriginalPrice(customerContractProductAddQO.getProductOriginalPrice());
                customerProductOrderDetail.setProductUnitPrice(customerContractProductAddQO.getProductUnitPrice());
                customerProductOrderDetail.setProductMemberPrice(customerContractProductAddQO.getProductMemberPrice());
                //判断产品是会员产品还是非会员产品
                if ("1".equals(customerContractProductAddQO.getProductCategories())) {
                    if(customerContractProductAddQO.getProductMemberPrice()!=null&&customerContractProductAddQO.getProductFinalPrice()!=null){
                        //会员产品的优惠价等于会员价减成交价，要是为负值就默认为零
                        BigDecimal productPreferentialPrice = customerContractProductAddQO.getProductMemberPrice().subtract(customerContractProductAddQO.getProductFinalPrice());
                        if (new BigDecimal("0").compareTo(productPreferentialPrice) == 1) {
                            customerProductOrderDetail.setProductPreferentialPrice(BigDecimal.ZERO);
                        } else {
                            customerProductOrderDetail.setProductPreferentialPrice(productPreferentialPrice);
                        }
                    }
                } else {
                    if (customerContractProductAddQO.getProductOriginalPrice() != null && customerContractProductAddQO.getProductFinalPrice() != null) {
                        //非会员产品的优惠价等于产品原价减成交价，要是为负值就默认为零
                        BigDecimal productPreferentialPrice = customerContractProductAddQO.getProductOriginalPrice().subtract(customerContractProductAddQO.getProductFinalPrice());
                        if (new BigDecimal("0").compareTo(productPreferentialPrice) == 1) {
                            customerProductOrderDetail.setProductPreferentialPrice(BigDecimal.ZERO);
                        } else {
                            customerProductOrderDetail.setProductPreferentialPrice(productPreferentialPrice);
                        }
                    }
                }
                customerProductOrderDetail.setProductFinalPrice(customerContractProductAddQO.getProductFinalPrice());
                customerProductOrderDetail.setProductQuantity(customerContractProductAddQO.getProductQuantity());
                customerProductOrderDetail.setProductOrderDetailType("1");
                UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
                customerProductOrderDetail.setCreatePeopleId(userAccount.getAccountId());
                customerProductOrderDetail.setCreateTm(new Date());
                customerProductOrderDetail.setUpdatePeopleId(userAccount.getAccountId());
                customerProductOrderDetail.setUpdateTm(new Date());
                customerProductOrderDetail.setOrderRelationId(customerContractProductAddQO.getProductId());
                customerProductOrderDetail.setProductOrderId(orderId);
                customerProductOrderDetail.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

                //如果合同类型是7会员单次合同,则重新赋产品值
                if ("7".equals(customerContractAddQO.getContractType())) {
                    customerProductOrderDetail.setProductCode("Cace6d");
                    customerProductOrderDetail.setOrderRelationId("dc2066c2292a40b2b2a009dd4f6d2662");
                    customerProductOrderDetail.setOrderDetailName("现场单次");
                    customerProductOrderDetail.setProductQuantity(1);
                    customerProductOrderDetail.setProductMemberPrice(BigDecimal.ZERO);
                    customerProductOrderDetail.setProductCategories("1");
                }
                customerProductOrderDetailDbService.insertCustomerProductOrderDetail(customerProductOrderDetail);
            });

        }
        //添加活动及其下产品
        List<CustomerActivityProductAddQO> customerActivityProductAddQOList = customerContractAddQO.getCustomerActivityProductAddQOList();
        if (customerActivityProductAddQOList != null && customerActivityProductAddQOList.size() > 0) {
            customerActivityProductAddQOList.stream().forEach(customerActivityProductAddQO -> {
                CustomerProductOrderDetail customerProductOrderDetail = new CustomerProductOrderDetail();
                customerProductOrderDetail.setProductOrderDetailId(CommonUtils.getGUID());
                customerProductOrderDetail.setOrderDetailName(customerActivityProductAddQO.getProductActivityName());
                customerProductOrderDetail.setProductOriginalPrice(customerActivityProductAddQO.getProductOriginalPrice());
                BigDecimal productPreferentialPrice = customerActivityProductAddQO.getProductOriginalPrice().subtract(customerActivityProductAddQO.getProductFinalPrice());
                if (new BigDecimal("0").compareTo(productPreferentialPrice) == 1) {
                    customerProductOrderDetail.setProductPreferentialPrice(BigDecimal.ZERO);
                } else {
                    customerProductOrderDetail.setProductPreferentialPrice(productPreferentialPrice);
                }
                customerProductOrderDetail.setProductFinalPrice(customerActivityProductAddQO.getProductFinalPrice());
                customerProductOrderDetail.setProductQuantity(customerActivityProductAddQO.getProductQuantity());
                customerProductOrderDetail.setProductOrderDetailType("2");
                UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
                customerProductOrderDetail.setCreatePeopleId(userAccount.getAccountId());
                customerProductOrderDetail.setCreateTm(new Date());
                customerProductOrderDetail.setUpdatePeopleId(userAccount.getAccountId());
                customerProductOrderDetail.setUpdateTm(new Date());
                customerProductOrderDetail.setOrderRelationId(customerActivityProductAddQO.getProductActivityId());
                customerProductOrderDetail.setProductOrderId(orderId);
                customerProductOrderDetail.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
                customerProductOrderDetailDbService.insertCustomerProductOrderDetail(customerProductOrderDetail);
                //插入订单-活动产品关联表
                List<JSONObject> productList = customerActivityProductAddQO.getProductList();
                for (JSONObject object : productList) {
                    CustomerOrderActivityRelation customerOrderActivityRelation = new CustomerOrderActivityRelation();
                    customerOrderActivityRelation.setOrderActivityRelationId(CommonUtils.getGUID());
                    customerOrderActivityRelation.setCustomerProductId(object.getString("productId"));
                    customerOrderActivityRelation.setProductName(object.getString("productName"));
                    customerOrderActivityRelation.setProductActivityId(customerActivityProductAddQO.getProductActivityId());
                    customerOrderActivityRelation.setProductOrderId(orderId);
                    customerOrderActivityRelation.setCreatePeopleId(userAccount.getAccountId());
                    customerOrderActivityRelation.setProductCategories(object.getString("productCategories"));
                    customerOrderActivityRelation.setProductFinalPrice(object.getBigDecimal("productFinalPrice"));
                    customerOrderActivityRelation.setCreateTm(new Date());
                    orderActivityRelationDbService.insert(customerOrderActivityRelation);
                }
            });
        }
        //添加赠品活动及其下产品
        List<CustomerGiftActivityProductAddQO> customerGiftActivityProductAddQOList = customerContractAddQO.getCustomerGiftActivityProductAddQOList();
        if (customerGiftActivityProductAddQOList != null && customerGiftActivityProductAddQOList.size() > 0) {
            customerGiftActivityProductAddQOList.stream().forEach(customerGiftActivityProductAddQO -> {
                CustomerProductOrderDetail customerProductOrderDetail = new CustomerProductOrderDetail();
                customerProductOrderDetail.setProductOrderDetailId(CommonUtils.getGUID());
                customerProductOrderDetail.setOrderDetailName(customerGiftActivityProductAddQO.getGiftActivityName());
                customerProductOrderDetail.setProductOrderDetailType("3");
                UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
                customerProductOrderDetail.setCreatePeopleId(userAccount.getAccountId());
                customerProductOrderDetail.setCreateTm(new Date());
                customerProductOrderDetail.setUpdatePeopleId(userAccount.getAccountId());
                customerProductOrderDetail.setUpdateTm(new Date());
                customerProductOrderDetail.setOrderRelationId(customerGiftActivityProductAddQO.getProductGiftActivityId());
                customerProductOrderDetail.setProductOrderId(orderId);
                customerProductOrderDetail.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
                customerProductOrderDetailDbService.insertCustomerProductOrderDetail(customerProductOrderDetail);

                //添加赠品活动下赠品
                List<CustomerGiftAddQO> customerGiftAddQOList = customerGiftActivityProductAddQO.getGiftProductList();
                if (customerGiftAddQOList.size() > 0) {
                    customerGiftAddQOList.stream().forEach(customerGiftAddQO -> {
                        CustomerOrderGiftRelation customerOrderGiftRelation = new CustomerOrderGiftRelation();
                        customerOrderGiftRelation.setOrderGiftRelationId(CommonUtils.getGUID());
                        customerOrderGiftRelation.setProductGiftName(customerGiftAddQO.getGiftProductName());
                        customerOrderGiftRelation.setGiftQuantity(customerGiftAddQO.getGiftQuantity());
                        customerOrderGiftRelation.setProductOriginalPrice(customerGiftAddQO.getGiftOriginalPrice());
                        customerOrderGiftRelation.setProductUnitPrice(customerGiftAddQO.getGiftUnitPrice());
                        customerOrderGiftRelation.setCreatePeopleId(userAccount.getAccountId());
                        customerOrderGiftRelation.setCreateTm(new Date());
                        customerOrderGiftRelation.setProductCategories(customerGiftAddQO.getProductCategories());
                        customerOrderGiftRelation.setProductGiftActivityId(customerGiftActivityProductAddQO.getProductGiftActivityId());
                        customerOrderGiftRelation.setCustomerProductId(customerGiftAddQO.getGiftProductId());
                        customerOrderGiftRelation.setProductOrderId(orderId);
                        customerOrderGiftRelation.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
                        customerOrderGiftRelationDbService.insertOrderGiftRelation(customerOrderGiftRelation);
                    });
                }
            });
        }
        return true;
    }


    /***
     * @Description: 审核管理-更新合同详情
     * @Author: luojie
     * @Date: 2021/3/31 8:55
     */
    @Override
    public Boolean updateContractReviewDetail(ContractReviewDetailQO contractReviewDetailQO) {
        //更新合同
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        CustomerContract customerContract = new CustomerContract();
        customerContract.setContractId(contractReviewDetailQO.getContractId());
        customerContract.setContractStartDate(contractReviewDetailQO.getContractStartDate());
        customerContract.setContractEndDate(contractReviewDetailQO.getContractEndDate());
        customerContract.setContractType(contractReviewDetailQO.getContractType());
        customerContract.setUpdateTm(new Date());
        customerContract.setUpdatePeopleId(userAccount.getAccountId());
        customerContract.setContactId(contractReviewDetailQO.getContactId());
        customerContract.setContactName(contractReviewDetailQO.getContactName());
        customerContract.setContactDetails(contractReviewDetailQO.getContactDetails());
        customerContract.setCustomerEmail(contractReviewDetailQO.getCustomerEmail());
        Boolean result = customerContractDbService.updateCustomerContract(customerContract);

        if(!StringUtils.isBlank(contractReviewDetailQO.getOrderId())){
            //更新订单
            CustomerProductOrder customerProductOrder = new CustomerProductOrder();
            customerProductOrder.setProductOrderId(contractReviewDetailQO.getOrderId());
            customerProductOrder.setContractType(contractReviewDetailQO.getContractType());
            customerProductOrder.setContactPerson(contractReviewDetailQO.getContactName());
            customerProductOrder.setBindMobilePhoneNumber(contractReviewDetailQO.getContactDetails());
            customerProductOrder.setCustomerEmail(contractReviewDetailQO.getCustomerEmail());
            customerProductOrder.setUpdatePeopleId(userAccount.getAccountId());
            customerProductOrder.setUpdateTm(userAccount.getUpdateTm());
            customerProductOrderDbService.updateProductOrder(customerProductOrder);
        }

        return result;
    }

    /***
     * @Description: 根据合同id查询合同续费信息
     * @Param:contractId 合同id
     * @Author: luojie
     * @Date: 2021/4/15 16:54
     */
    @Override
    public ContractRenewalVO selectContractRenewalInformation(String contractId, Integer pageIndex, Integer pageSize) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        ContractRenewalVO contractRenewalVO = new ContractRenewalVO();
        CustomerContract customerContract = customerContractDbService.selectContractById(contractId);
        contractRenewalVO.setCustomerId(customerContract.getCustomerId());
        contractRenewalVO.setContactId(customerContract.getContactId());
        contractRenewalVO.setContactName(customerContract.getContactName());
        contractRenewalVO.setContactDetails(customerContract.getContactDetails());
        contractRenewalVO.setCustomerEmail(customerContract.getCustomerEmail());
        contractRenewalVO.setContractStartDate(customerContract.getContractStartDate());
        contractRenewalVO.setContractEndDate(customerContract.getContractEndDate());
        contractRenewalVO.setApplyElectronicContract(customerContract.getApplyElectronicContract());
        contractRenewalVO.setContractAnnexId(customerContract.getReviewAnnexId());
        contractRenewalVO.setPaymentMethod(customerContract.getPaymentMethod());
        contractRenewalVO.setPaymentNumber(customerContract.getPaymentNumber());
        //合同附件上传id
        if (!StringUtils.isBlank(customerContract.getContractAnnexId())) {
            FileUpload fileUploadAnnexId = fileUploadService.selectFileUploadById(customerContract.getContractAnnexId());
            if (fileUploadAnnexId != null) {
                contractRenewalVO.setContractAnnexId(contractRenewalVO.getContractAnnexId());
                contractRenewalVO.setContractAnnexAccessUrl(fileUploadAnnexId.getAccessUrl());
            }
        }

        //审核附件id
        if (!StringUtils.isBlank(customerContract.getReviewAnnexId())) {
            FileUpload fileUploadReviewAnnexId = fileUploadService.selectFileUploadById(customerContract.getReviewAnnexId());
            if (fileUploadReviewAnnexId != null) {
                contractRenewalVO.setReviewAnnexId(customerContract.getReviewAnnexId());
                contractRenewalVO.setReviewAnnexAccessUrl(fileUploadReviewAnnexId.getAccessUrl());
            }
        }

        //查询审批会员产品对象
        List<CustomerProductOrderDetailEditVO> productOrderDetailEditVOList = new ArrayList<>();
        List<FinishOrderProduct> finishOrderProductList = finishOrderDBservice.selectFinishOrderProductList("1", customerContract.getOrderId());
        PageInfo<FinishOrderProduct> pageInfo = new PageInfo<>(finishOrderProductList);
        pageInfo.getList().stream().forEach(finishOrderProduct -> {
            CustomerProductOrderDetailEditVO customerProductOrderDetailEditVO = new CustomerProductOrderDetailEditVO();
            customerProductOrderDetailEditVO.setProductName(finishOrderProduct.getProductName());
            customerProductOrderDetailEditVO.setProductCode(finishOrderProduct.getProductCode());
            customerProductOrderDetailEditVO.setProductCategories("1");
            customerProductOrderDetailEditVO.setProductOriginalPrice(finishOrderProduct.getProductOriginalPrice());
            customerProductOrderDetailEditVO.setProductUnitPrice(finishOrderProduct.getProductUnitPrice());
            customerProductOrderDetailEditVO.setProductMemberPrice(finishOrderProduct.getProductMemberPrice());
            customerProductOrderDetailEditVO.setProductDiscountPrice(finishOrderProduct.getProductPreferentialPrice());
            customerProductOrderDetailEditVO.setProductFinalPrice(finishOrderProduct.getProductFinalPrice());
            customerProductOrderDetailEditVO.setProductNumber(finishOrderProduct.getProductQuantity());
            customerProductOrderDetailEditVO.setCustomerProductId(finishOrderProduct.getProductId());
            productOrderDetailEditVOList.add(customerProductOrderDetailEditVO);
        });
        contractRenewalVO.setProductEditArr(new DhPageInfo<CustomerProductOrderDetailEditVO>(pageInfo, productOrderDetailEditVOList));
        return contractRenewalVO;
    }

    /***
     * @Description:根据合同id查询合同信息
     * @Param: contractId 合同id
     * @Author: luojie
     * @Date: 2021/4/19 8:38
     */
    @Override
    public ContractRenewalAddVO selectContractById(String contractId) {
        ContractRenewalAddVO contractRenewalAddVO = new ContractRenewalAddVO();
        CustomerContract customerContract = customerContractDbService.selectContractById(contractId);
        BeanUtils.copyProperties(customerContract, contractRenewalAddVO);
        List<String> coDevelopIdList = new ArrayList<>();
        List<CustomerContractDeveloper> developerList = customerContractDeveloperDbService.selectCustomerContractDeveloperList(contractId);

        developerList.stream().forEach(customerContractDeveloper -> {
            coDevelopIdList.add(customerContractDeveloper.getCoDeveloper());
        });
        contractRenewalAddVO.setCoDeveloperList(coDevelopIdList);
        return contractRenewalAddVO;
    }

    /***
     * @Description:根据合同编号查询合同信息
     * @Param: contractNumber 合同编号
     * @Author: luojie
     * @Date: 2021/6/1 14:46
     */
    @Override
    public ContractRenewalAddVO selectContractByContractNumber(String contractNumber) {
        ContractRenewalAddVO contractRenewalAddVO = new ContractRenewalAddVO();
        CustomerContract customerContract = customerContractDbService.selectContractByContractNumber(contractNumber);
        BeanUtils.copyProperties(customerContract, contractRenewalAddVO);
        return contractRenewalAddVO;
    }

    /***
     * @Description:查询未回款合同
     * @Author: luojie
     * @Date: 2021/4/26 9:48
     */
    @Override
    public DhPageInfo<ContractUnpaidVO> selectUnpaidContract() {
        //设定显示5条数据
        Integer pageIndex = 1;
        Integer pageSize = 5;
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        List<ContractUnpaidVO> contractUnpaidVOList = new ArrayList<>();
        List<CustomerContract> customerContractList = customerContractDbService.selectUnpaidContract();
        PageInfo<CustomerContract> pageInfo = new PageInfo<>(customerContractList);
        pageInfo.getList().stream().forEach(customerContract -> {
            ContractUnpaidVO contractUnpaidVO = new ContractUnpaidVO();
            contractUnpaidVO.setContractNumber(customerContract.getContractNumber());
            contractUnpaidVO.setContractTotalAmount(customerContract.getContractTotalAmount());
            contractUnpaidVO.setCreateTm(customerContract.getCreateTm());
            contractUnpaidVOList.add(contractUnpaidVO);
        });
        return new DhPageInfo<ContractUnpaidVO>(pageInfo, contractUnpaidVOList);
    }

    /**
     * 商机详情-查询商机客户下面未过期的合同
     *
     * @param customerId 客户id
     * @return
     */
    @Override
    public List<CustomerContractVO> opportunityCustomerContract(String customerId) {
        List<CustomerContractVO> list = new ArrayList<>();
        Customer customer = customerDbService.selectCustomerById(customerId);
        if (customer.getMembershipExpirationTm() == null) {
            return list;
        } else {
            Date nowDate = new Date();
            Date thereMonthDate = yearAddNum(customer.getMembershipExpirationTm(), 3);

            //compareTo()方法的返回值，date1小于date2返回-1，date1大于date2返回1，相等返回0
            int compareTo = thereMonthDate.compareTo(nowDate);
            if (compareTo == -1) {
                return list;
            } else {
                list = customerContractDbService.selectByCustomerId(customer.getCustomerId());
                return list;
            }
        }

    }

    public static Date yearAddNum(Date time, Integer num) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.add(Calendar.MONTH, num);
        Date newTime = calendar.getTime();
        return newTime;
    }


    /**
     * @Description: 通过合同编号获取数据
     * @Param: [contractNum]
     * @Return: java.util.List<com.crm.model.vo.datasearch.DataSearchResultVO>
     * @Author: lixq-f
     * @Date: 2021/5/13
     **/
    @Override
    public List<DataSearchResultVO> selectDataByContractNum(String contractNum) {
        return customerContractDbService.selectDataByContractNum(contractNum);
    }


    /**
     * @Description: 查询单品合同列表
     * @Param: [customerContractQO, pageIndex, pageSize, sortName, sortOrder]
     * @Return: com.crm.common.model.DhPageInfo<com.crm.model.vo.customerContractManager.CustomerContractVO>
     * @Author: lixq-f
     * @Date: 2021/6/17
     **/
    @Override
    public DhPageInfo<CustomerContractVO> selectSingleContractList(CustomerContractQO customerContractQO,
                                                                   Integer pageIndex, Integer pageSize,
                                                                   String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());

        customerContractQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
        //单品合同
        customerContractQO.setContractType("6");

        List<CustomerContractVO> resultList = null;
        if (Objects.nonNull(customerContractQO.getBs()) && customerContractQO.getBs() == 0) {
            if (rs) {
                //超级管理员
                resultList =
                        customerContractDbService.selectSingleContractList(customerContractQO, getOrder(sortName, sortOrder));
            } else {
                //普通管理员
                customerContractQO.setCompanyId(userAccount.getCompanyId());
                resultList =
                        customerContractDbService.selectSingleContractList(customerContractQO, getOrder(sortName, sortOrder));
            }
        } else {
            //普通用户
            customerContractQO.setAccountId(userAccount.getAccountId());
            resultList =
                    customerContractDbService.selectSingleContractList(customerContractQO, getOrder(sortName, sortOrder));
        }

        if (CollectionUtils.isEmpty(resultList)) {
            resultList = Lists.newArrayList();
        }

        PageInfo<CustomerContractVO> pageInfo = new PageInfo<>(resultList);
        return new DhPageInfo<>(pageInfo, resultList);
    }


    private String getOrder(String sortName, String sortOrder) {
        String order = " t.create_tm desc";
        if (StringUtils.isEmpty(sortName) && StringUtils.isEmpty(sortOrder)) {
            return order;
        }
        if ("createTm".equals(sortName)) {
            order = " t.create_tm " + sortOrder;
        }
        return order;
    }

    /**
     * 业务员更新审核失败合同
     * @param customerContractUpdateQO
     * @return
     */
    @Override
    public Boolean updateReviewFailedContract(CustomerContractUpdateQO customerContractUpdateQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        //更新合同
        //先根据合同id查询合同基本信息
        CustomerContract customerContract = customerContractDbService.selectContractById(customerContractUpdateQO.getContractId());
        customerContract.setContactId(customerContractUpdateQO.getContactId());
        customerContract.setContactName(customerContractUpdateQO.getContactName());
        customerContract.setContactDetails(customerContractUpdateQO.getContactDetails());
        customerContract.setContractStartDate(customerContractUpdateQO.getContractStartDate());
        customerContract.setContractEndDate(customerContractUpdateQO.getContractEndDate());
        //合同审核状态设置为未审核
        customerContract.setContractReviewStatus("0");
        //合同审核状态设置为未生效合同状态:1-未生效；2-生效中；3-已结束；4-已作废；5-意外终止；6-挂起
        //customerContract.setContractStatus("1"); 设置状态可能有问题，恢复合同状态还得判断商机可不可用
        customerContract.setReviewerId("");
        customerContract.setReviewerName("");
        customerContract.setReviewTime(null);
        customerContract.setUpdatePeopleId(userAccount.getAccountId());
        customerContract.setUpdateTm(new Date());
        Boolean result = customerContractDbService.updateCustomerContractWithAllModel(customerContract);

        //更新订单
        CustomerProductOrder customerProductOrder = new CustomerProductOrder();
        customerProductOrder.setProductOrderId(customerContractUpdateQO.getOrderId());
        customerProductOrder.setContactPerson(customerContractUpdateQO.getContactName());
        //订单状态--1:等待回款;2:已完成;3:作废;4:部分回款（回款维护）设置状态可能有问题
        //customerProductOrder.setOrderStatus("1");
        customerProductOrder.setBindMobilePhoneNumber(customerContractUpdateQO.getContactDetails());
        customerProductOrder.setUpdatePeopleId(userAccount.getAccountId());
        customerProductOrder.setUpdateTm(new Date());
        customerProductOrderDbService.updateProductOrder(customerProductOrder);
        return result;
    }

    @Override
    public DhPageInfo<CustFinanceProductOderVO> getMemberProductList(Integer pageIndex, Integer pageSize, String sortName, String sortOrder, String orderId, String productCategories) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //增加删除状态查询条件(0:正常;1:已删除)
        short delState = (short) StatusCodeEnum.NORMAL_CODE.getState();


        List<CustFinanceProductOderVO> list = finishOrderDBservice.getMemberProductListByOrderId(delState, orderId,productCategories);
        PageInfo<CustFinanceProductOderVO> pageInfo = new PageInfo<CustFinanceProductOderVO>(list);
        return new DhPageInfo<CustFinanceProductOderVO>(pageInfo, list);
    }

    /***
     * @Description: 根据客户id查询合同联系人列表
     * @Param: customerId 客户id
     * @param auditStatus 联系人审核状态
     * @param onTheJobSituation 职业状态
     * @Author: luojie
     * @Date: 2021/9/2 10:22
     */
    @Override
    public DhPageInfo<ContractContactVO> selectContractContactList(String customerId, Integer pageIndex, Integer pageSize, String sortName, String sortOrder,String auditStatus,String onTheJobSituation) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        //排序
        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("c.create_tm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }

        }

        List<Integer> auditStatusList = JSONArray.parseArray(auditStatus,Integer.class);
        List<Integer> onTheJobSituationList = JSONArray.parseArray(onTheJobSituation,Integer.class);
        List<ContractContactVO> customerContractList =  customerContractDbService.selectContractContactByCustomerId(customerId,order.toString(),auditStatusList,onTheJobSituationList);
        PageInfo<ContractContactVO> pageInfo = new PageInfo<ContractContactVO>(customerContractList);
        return new DhPageInfo<ContractContactVO>(pageInfo, customerContractList);
    }

    /***
     * @Description:根据合同id更新合同联系人
     * @Param:CustomerContractUpdateQO
     * @Author: luojie
     * @Date: 2021/9/2 22:55
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean updateContractContactByContractId(ContractContactUpdateQO contractContactUpdateQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        //查询合同联系人
        CustomerContract customerContract = customerContractDbService.selectContractById(contractContactUpdateQO.getContractId());
        //更新联系人姓名保存日志表
        if(!StringUtils.isBlank(contractContactUpdateQO.getContactName())&&!customerContract.getContactName().equals(contractContactUpdateQO.getContactName())){
            CustomerContract contractContactName = new CustomerContract();
            contractContactName.setContractId(contractContactUpdateQO.getContractId());
            contractContactName.setContactName(contractContactUpdateQO.getContactName());
            contractContactName.setContactReviewStatus(contractContactUpdateQO.getAuditStatus());
            customerContractDbService.updateCustomerContract(contractContactName);

            CustomerServiceWorkLog customerServiceWorkLog = new CustomerServiceWorkLog();
            customerServiceWorkLog.setWorkLogId(CommonUtils.getGUID());
            customerServiceWorkLog.setLogType(WorkLogEnum.LOG_TYPE_CONTRACT_CONTACT.getCode().shortValue());
            customerServiceWorkLog.setLogContent("客服部将合同编号"+ customerContract.getContractNumber() + "的联系人姓名由"+customerContract.getContactName()+
                    "改为" + contractContactUpdateQO.getContactName());
            customerServiceWorkLog.setLogRemark(contractContactUpdateQO.getRemarks()+ " " + userAccount.getUserName());
            customerServiceWorkLog.setCreatePeopleId(userAccount.getAccountId());
            customerServiceWorkLog.setCreateTm(new Date());
            customerServiceWorkLog.setUpdatePeopleId(userAccount.getAccountId());
            customerServiceWorkLog.setUpdateTm(new Date());
            customerServiceWorkLog.setCustomerId(customerContract.getCustomerId());
            customerServiceWorkLog.setRelationId(customerContract.getContractId());
            customerServiceWorkLog.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
            serviceWorkLogDbService.insertWorkLog(customerServiceWorkLog);
        }

        //更新联系人方式保存日志表
        if(!StringUtils.isBlank(contractContactUpdateQO.getContactDetails())&&!customerContract.getContactDetails().equals(contractContactUpdateQO.getContactDetails())){
            CustomerContract contractContactName = new CustomerContract();
            contractContactName.setContractId(contractContactUpdateQO.getContractId());
            contractContactName.setContactDetails(contractContactUpdateQO.getContactDetails());
            contractContactName.setContactReviewStatus(contractContactUpdateQO.getAuditStatus());
            customerContractDbService.updateCustomerContract(contractContactName);

            CustomerServiceWorkLog customerServiceWorkLog = new CustomerServiceWorkLog();
            customerServiceWorkLog.setWorkLogId(CommonUtils.getGUID());
            customerServiceWorkLog.setLogType(WorkLogEnum.LOG_TYPE_CONTRACT_CONTACT.getCode().shortValue());
            customerServiceWorkLog.setLogContent("客服部将合同编号"+ customerContract.getContractNumber() + "的联系人联系方式由"+customerContract.getContactDetails()+
                    "改为" + contractContactUpdateQO.getContactDetails());
            customerServiceWorkLog.setLogRemark(contractContactUpdateQO.getRemarks());
            customerServiceWorkLog.setCreatePeopleId(userAccount.getAccountId());
            customerServiceWorkLog.setCreateTm(new Date());
            customerServiceWorkLog.setUpdatePeopleId(userAccount.getAccountId());
            customerServiceWorkLog.setUpdateTm(new Date());
            customerServiceWorkLog.setCustomerId(customerContract.getCustomerId());
            customerServiceWorkLog.setRelationId(customerContract.getContractId());
            customerServiceWorkLog.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());
            serviceWorkLogDbService.insertWorkLog(customerServiceWorkLog);
        }
        return true;
    }

    /**
     * 合同的一些调整
     * @param contractNumber 合同编号
     * @param orderNumber 订单编号
     * @param customerName 客户名称
     * @param userName 用户名称
     * @param bs  1调整生效合同 2补全客户信息和登录人信息 3补全客户信息 4补全登录人信息
     * @return
     */
    @Override
    public String adjustmentContract(String contractNumber, String orderNumber, String customerName, String userName, String bs) {

        if(StringUtils.isBlank(contractNumber)) {
            return "合同编号不能为空";
        }
        if(StringUtils.isBlank(orderNumber)) {
            return "合同编号不能为空";
        }

        CustomerContract contract = customerContractDbService.selectContractByContractNumber(contractNumber);
        CustomerProductOrder order = customerProductOrderDbService.selectCustomerProductOrderById(contract.getOrderId());

        if("1".equals(bs)) {
            contract.setContractStatus("2");
            contract.setContractReviewNotes("手动调整合同生效");
            order.setOrderStatus("2");

        }
        if("2".equals(bs)) {
            if(StringUtils.isBlank(customerName)) {
                return "客户名称不能为空";
            }
            if(StringUtils.isBlank(userName)) {
                return "用户名称不能为空";
            }

            Customer customer = customerDbService.selectByCustomerName(customerName);
            UserAccount userAccount = userAccountService.selectUserAccountByUserName(userName);
            contract.setCustomerId(customer.getCustomerId());
            contract.setCustomerName(customer.getCustomerName());
            contract.setCreatePeopleId(userAccount.getAccountId());
            order.setCustomerId(customer.getCustomerId());
            order.setCustomerName(customer.getCustomerName());
            order.setCreatePeopleId(userAccount.getAccountId());

        }

        if("3".equals(bs)) {
            if(StringUtils.isBlank(customerName)) {
                return "客户名称不能为空";
            }
            Customer customer = customerDbService.selectByCustomerName(customerName);
            contract.setCustomerId(customer.getCustomerId());
            contract.setCustomerName(customer.getCustomerName());
            order.setCustomerId(customer.getCustomerId());
            order.setCustomerName(customer.getCustomerName());
        }


        if("4".equals(bs)) {
            if(StringUtils.isBlank(userName)) {
                return "用户名称不能为空";
            }
            UserAccount userAccount = userAccountService.selectUserAccountByUserName(userName);
            contract.setCreatePeopleId(userAccount.getAccountId());
            order.setCreatePeopleId(userAccount.getAccountId());

        }

        Boolean rs = customerContractDbService.updateCustomerContract(contract);
        Boolean res = customerProductOrderDbService.updateByPrimaryKeySelective(order);
        if(rs == res) {
            return "成功";
        }else{
            return "失败";
        }

    }
}
